How do I query a string from JSON based on another string within the JSON in PostgreSQL?

北城余情 提交于 2020-01-16 08:08:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!