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
-
1Tips for asking a good Structured Query Language (SQL) question, #5 and #3.Akina– Akina2024年06月04日 09:48:05 +00:00Commented 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.Community– Community Bot2024年06月04日 15:18:06 +00:00Commented Jun 4, 2024 at 15:18
2 Answers 2
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
TL;DR:
select
json_array_elements(
json_array_elements(
json->'components'
)->'manufacturers'
)->>'country' as component_manufacturer_country
from foo
See 9.16. JSON Functions and Operators.
From the inmost part of the expression to the outer:
->
indexes to thecomponents
attributes asjson
- because
components
is an array, we split to rows usingjson_array_elements()
- repeat steps 1 & 2 with the
manufacturers
attribute ->>
indexes to thecountry
attribute astext
answered Jun 4, 2024 at 12:34
lang-sql