0

I want to return Germany and UK from the below json column/string.

{
 "id": 1,
 "name": "phone",
 "components": [
 {
 "id": 1,
 "type": "screen",
 "manufacturers": [
 {
 "id": 1,
 "name": "a",
 "country": "Germany"
 }
 ]
 },
 {
 "id": 2,
 "type": "keyboard",
 "manufacturers": [
 {
 "id": 1,
 "name": "a",
 "country": "UK"
 }
 ]
 }
 ]
}
Akina
20.8k2 gold badges20 silver badges22 bronze badges
asked Jun 4, 2024 at 9:13
2
  • 1
    Tips for asking a good Structured Query Language (SQL) question, #5 and #3. Commented Jun 4, 2024 at 9:48
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Jun 4, 2024 at 15:18

2 Answers 2

1

Using a JSONPATH query, that should be simple:

SELECT * FROM jsonb_path_query('your JSON string', 'strict $.**.country');
 jsonb_path_query 
══════════════════
 "Germany"
 "UK"
(2 rows)
answered Jun 5, 2024 at 7:18
0

TL;DR:

select 
 json_array_elements(
 json_array_elements(
 json->'components'
 )->'manufacturers'
 )->>'country' as component_manufacturer_country
from foo

fiddle

See 9.16. JSON Functions and Operators.

From the inmost part of the expression to the outer:

  1. -> indexes to the components attributes as json
  2. because components is an array, we split to rows using json_array_elements()
  3. repeat steps 1 & 2 with the manufacturers attribute
  4. ->> indexes to the country attribute as text
answered Jun 4, 2024 at 12:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.