2

How can json_extract be used to look through all objects in an array? It works if you knew the key, but I want to look at every single object and find the one that matches.

$.features[0].properties.TMPRIV_ID

How to get this to work?

$.features[*].properties.TMPRIV_ID
1
  • That code is not SQL. And standard SQL does not have a json_extract function. And why did you tag two different databases? Commented Aug 1, 2018 at 19:18

1 Answer 1

6

You have this flagged with MySQL and Sqlite, so I'm going to flip a coin and give a Sqlite answer.

Basically, you need to select from the json_each() row-valued function to iterate over each element of the array, and a where clause that filters just what you want (Which is where json_extract() comes into play):

sqlite> SELECT value FROM
  json_each('[{"name":"cat","type":"mammal"},{"name":"parrot","type":"bird"},{"name":"dog","type":"mammal"}]')
  WHERE json_extract(value, '$.type') = 'mammal';
value                         
------------------------------
{"name":"cat","type":"mammal"}
{"name":"dog","type":"mammal"}

If you want the results as a JSON array instead of a set of rows, use the json_group_array() aggregate function: SELECT json_group_array(value) FROM ...

Sign up to request clarification or add additional context in comments.

2 Comments

Ah I see, you the json_each loops through it, nice! thanks!
@mobeen Not a clue. I don't use MySQL.

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.