0

My Table

create table i (a json)

Insert:

insert into i values ('[[1300,[{"id":5,"time":1451423706048,"zon":0,"name":"AMighty","loc":"ny"},[[3405,0,1000],[35,0,1000],[3401,0,10000],[2541,0,1000]]]]]' )

I wish to extract the field which comes after 2541. in that case the answer 0

When querying my Json with:

select json_array_elements(a) from I

it returns only one row.

1 Answer 1

2

You need to go through all the nested arrays to get necessary element:

WITH i(a) AS ( VALUES
  ('[[1300,[{"id":5,"time":1451423706048,"zon":0,"name":"AMighty","loc":"ny"},[[3405,0,1000],[35,0,1000],[3401,0,10000],[2541,0,1000]]]]]'::JSON)
)
SELECT
  array_element->1->1->3 as array_you_look_for,
  array_element->1->1->3->1 as inner_array_element
FROM i,
  json_array_elements(a) as array_element;

Output:

 array_you_look_for | inner_array_element 
--------------------+---------------------
 [2541,0,1000]      | 0
(1 row)
Sign up to request clarification or add additional context in comments.

11 Comments

can you clarify this syntax: FROM i, json_array_elements(a) as array_element; what relation is created?
what do you mean? after FROM clause you can specify one or more sources to select from - check postgresql.org/docs/9.4/static/sql-select.html @koriander
I'm not familiar with postgresql specifities and that page is not clear on this point, but the comma is usually a cartesian join, so the second part should be a relation. But how come json_array_elements(a) knows it refers to field 'a' of table i.
and why not simply do SELECT a->0->1->1->3->1 from i
Dmitry, Is there is away which I can take the 2541 as a field and not by location?
|

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.