I have a table with several fields (id, title, json_field). I want to select all rows from this table, but I want each parameter inside json_field to be a separate row in result. I guess I should use json_array_elements, but the problem is that I can't understand how to include it in my query.
Is there are solution? I expected it to work with with this query:
select id, title, json_array_elements(json_field) from table_name, but it doesn't.
I also tried to pass subquery result as an argument, not succeeded as well.
I read through the docs (http://www.postgresql.org/docs/9.3/static/functions-json.html) but I can't find anything helpful.
Thanks a lot for the help!
-
Show the json valuesClodoaldo Neto– Clodoaldo Neto2014年09月01日 12:13:42 +00:00Commented Sep 1, 2014 at 12:13
-
2Do you get an error? or how exactly it does not work?Bulat– Bulat2014年09月01日 12:25:41 +00:00Commented Sep 1, 2014 at 12:25
-
when you ask questions please provide table definitions, sample data and expected results. otherwise it is too much guesswork.Bulat– Bulat2014年09月01日 12:39:11 +00:00Commented Sep 1, 2014 at 12:39
2 Answers 2
I have tried to apply json_array_elements() function to VARCHAR and TEXT fields and it does not work:
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
However, it seems to work fine with JSON type. See SqlFiddle: http://sqlfiddle.com/#!15/2977f/3
So all you need to do is to cast your field to JSON data type: http://sqlfiddle.com/#!15/0fa19/1
1 Comment
Works for me
select 1, 2, json_array_elements('[1,true, [2,false]]');
?column? | ?column? | json_array_elements
----------+----------+---------------------
1 | 2 | 1
1 | 2 | true
1 | 2 | [2,false]
Also works with a table
select id, title, json_array_elements(j) as j
from (values
(1, 'the title', '[1,true, [2,false]]'::json)
) s(id, title, j);
id | title | j
----+-----------+-----------
1 | the title | 1
1 | the title | true
1 | the title | [2,false]