问题
MyTable.MyField in my PostgreSQL database contains the following (simplified) JSON block:
{
"base": {
"fields": [
{
"fieldid": "c12f",
"fieldname": "sizes",
"choices": [
{
"choiceid": "2db3",
"size": "small"
},
{
"choiceid": "241f",
"size": "medium"
},
{
"choiceid": "3f52",
"size": "large"
}
],
"answer": "241f"
}
]
}
}
How can I use the value of answer
to extract the chosen size
from the choices
array please (i.e. in this case "medium")?
(Note: I have tried. For a TLDR version of this question see Trying to construct PostgreSQL Query to extract from JSON a text value in an object, in an array, in an object, in an array, in an object .)
Thank you.
回答1:
You can use json_array_elements in a lateral join, then just query the fields that you are looking for:
SELECT
field -> 'fieldid' AS id,
choice -> 'size' AS size
FROM
my_table,
json_array_elements(json_column -> 'base' -> 'fields') field,
json_array_elements(field -> 'choices') choice
WHERE
field ->> 'answer' = choice ->> 'choiceid'
来源:https://stackoverflow.com/questions/59079358/how-do-i-query-a-string-from-json-based-on-another-string-within-the-json-in-pos