Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select a nested item of json datatype?

I have a MySQL table named computers with a column named details that is json data type formatted. I’ve inserted a value like this in that column:

'{ "name": "Chrome", "os": "Windows", "resolution": { "x": 1680, "y": 1050 } }'

I can simple get Chrome value by the following query:

SELECT details ->> '$.name' FROM computers

Now I want to know, how can I get 1680 value (which is the value of x) ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can alter your query to:

SELECT details ->> '$.resolution.x' AS details FROM computers

Or use JSON_EXTRACT:

SELECT JSON_EXTRACT(details, '$.resolution.x') AS details FROM computers

Result:

| details  |
|----------|
| 1680     |

Fiddle here.

Note: As mentioned above, its not good practice to store information you plan on retrieving in a JSON column, create a dedicated value to store this information.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading