0

I've looked at example after example, and I cannot find the syntax for what I need to do. With the below jsonb data, can someone tell me how to query the lastUpdatedTimestamp?

{
    "name": "Company name",
    "professionalData": [{
            "unit": "unit 1",
            "id": "1228",
            "school": "University of California-Berkeley, Haas School of Business",
            "quarter": "Q1",
            "lastUpdatedTimestamp": "2020-10-27T18:05:00Z"
        },
        {
            "unit": "unit 2",
            "id": "1228",
            "school": "University of California-Berkeley, Haas School of Business",
            "quarter": "Q1",
            "lastUpdatedTimestamp": "2020-10-29T12:10:00Z"
        }
    ]
}

I can get the professionalData object, but how do I then get an element within the array nested in professionalData? This is my exact query:

SELECT 
    elements
FROM product_reference_master p,
    jsonb_array_elements(p.prd_ref_dta_mas_json->'professionalData') as elements

And I get an error: ERROR: cannot extract elements from an object

I'm using Postgresql Aurora in AWS. I'm unsure of the exact version...

2
  • Always specify the version you are using. Commented Jan 20, 2021 at 16:51
  • Thanks, of course. I'll edit my question. Commented Jan 20, 2021 at 16:51

1 Answer 1

1

demos:db<>fiddle

Expand the array with json_array_elements() and then you can query the inserted fields:

SELECT 
    elements -> 'lastUpdatedTimestamp'
FROM product_reference_master p,
    json_array_elements(p.prd_ref_json::jsonb->'professionalData') as elements

From Postgres 12, you can use json_path_query() alternatively:

SELECT
    *
FROM product_reference_master p,
    jsonb_path_query(p.prd_ref_json, '$.**.lastUpdatedTimestamp') as elements
Sign up to request clarification or add additional context in comments.

8 Comments

I tried something like that, but I get this error: ERROR: cannot extract elements from a scalar. professionalData is an object, not an array. Instead, it contains an array.
Then something else seems to be wrong: For me it works: dbfiddle.uk/… Please try to reproduce your setting in the fiddle and share the related link afterwards
Updated the answer
My fiddle works as well, but the example isn't applying to my database. I still get an error that professionalData is a scalar object. dbfiddle.uk/…
Maybe not all your data is type JSON? stackoverflow.com/questions/50296102/… Meaning: Your are casting text into json. Maybe not every record contains the expected structure?
|

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.