0

I'm trying to return the "value": "Brunswick" WHERE "language": "en" from the JSON string bellow

This returns the first in the list I don't know the index in the actual data

SELECT id, names->'common'->0->>'value' AS name FROM test;

Where as this returns 1, null

SELECT id,names @@ '$.common[*].value' AS en_name  FROM test
WHERE names @@ '$.common[*].language == "en"'

The above from here how to query for values in a deep nested json array in Postresql?

Also tried jsonb_path_query from Postgres find in jsonb nested array

Table with Cut down JSON string

    INSERT INTO test(id,names) VALUES(1,'{
  "short": null,
  "common": [
    {
      "value": "برونشوايغ",
      "language": "ar"
    },
    {
      "value": "Brunswick",
      "language": "en"
    }
  
  ]
}');

Here's my https://dbfiddle.uk/UiXTG8Vo

The plan is to update the en_name column with the returned value

2
  • "Also tried jsonb_path_query from Postgres find in jsonb nested array" - what exactly did you try? Commented Dec 2, 2023 at 12:36
  • At the bottom of the fiddle SELECT id,'common'->>'name_value' AS en_name, 'common'->>'language' AS language FROM test, JSONB_ARRAY_ELEMENTS(names->'common') AS common JSONB_ARRAY_ELEMENTS(common->'value') as name_value, JSONB_ARRAY_ELEMENTS(common->'language') AS language WHERE language = 'en'; Commented Dec 2, 2023 at 12:40

1 Answer 1

1

You have only a single level of array nesting, so you need jsonb_array_elements only once:

SELECT id, name->>'value' AS en_name
FROM test, jsonb_array_elements(names->'common') AS name
WHERE name->>'language' = 'en';

The corresponding json path expression would be

SELECT id, jsonb_path_query(names, '$.common[*]?(@.language == "en").value') AS en_name
FROM test;

(Updated fiddle)

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

2 Comments

Thank you! The first is easier to read and the second is a 1 liner. Are there any advantages in using either approach?
@Holly Not that I know.

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.