0

I have tried and facing issue while reading json column in PostgreSQL table. below is the table description.

task=# \d quots                                           
       Table "public.quots"
      Column      |  Type   | Modifiers 
------------------+---------+-----------
 items            | json    | 
 id               | integer | 
 supplier_id      | integer | 

Here is the data in table.

select items from quots limit 1;
                                                    items
-----------------------------------------------------------------------------------------------------------------------------------
 [{"item1":[{"id":5,"name":"Item Name","unitPrice":{"original":10.0,"converted":10.0}}],"item2":{"id":75,"name":"Name"},"id":23653}]

Now when I try to query and get item1, it return empty.

select items->'item1' from quots limit 1;
 ?column? 
----------

(1 row)

Any Clue?

PostgreSQL 9.4.4 PSQL 9.4.4

1 Answer 1

2

The json value is an array. You can select its first element using items->0:

select items->0->'item1' from quots limit 1;

                                   ?column?                                   
------------------------------------------------------------------------------
 [{"id":5,"name":"Item Name","unitPrice":{"original":10.0,"converted":10.0}}]
(1 row)
Sign up to request clarification or add additional context in comments.

2 Comments

When I try to use array_to_json(items->0->'item1') it returns. ERROR: cannot deconstruct an array as an object
I can not help you without seeing the context. Ask a new question containing data causing the error.

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.