1

I have JSON stored in MySQL, which has multiple objects with no key. An example:

[
{
    "glosses": [
        "cascade, rapids, cataract"
    ],
    "raw_glosses": [
        "cascade, rapids, cataract"
    ]
},
{
    "glosses": [
        "waterfall"
    ],
    "raw_glosses": [
        "waterfall"
    ]
},
{
    "glosses": [
        "the sound of a strong water stream"
    ],
    "raw_glosses": [
        "the sound of a strong water stream"
    ]
}
]

How is it possible to select each object by numeric key? For example:

SELECT senses[0], senses[2] FROM table WHERE id = 1;
1
  • 1
    If you're going to store data in JSON columns in MySQL, you should read the documentation on the builtin JSON functions: dev.mysql.com/doc/refman/8.0/en/json-functions.html and also do some practice. Try them out on some test data, and make sure you know how to use each one. Commented Mar 23, 2022 at 17:56

1 Answer 1

2

Using JSON_EXTRACT, you can select objects by key ($[0]).

SELECT JSON_EXTRACT( senses, '$[0]'), JSON_EXTRACT( senses, '$[1]'), JSON_EXTRACT( senses, '$[2]'), senses FROM table WHERE id = 1;

Result:

{"glosses": ["cascade, rapids, cataract"], "raw_glosses": ["cascade, rapids, cataract"]}

{"glosses": ["waterfall"], "raw_glosses": ["waterfall"]}

{"glosses": ["the sound of a strong water stream"], "raw_glosses": ["the sound of a strong water stream"]}
Sign up to request clarification or add additional context in comments.

1 Comment

senses->'$[0]' is... at least it is in short JSON_EXTRACT.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.