0

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 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. I considered editing it because I think I picked up a few typos but as I'm a bit of a novice in PostgreSQL and JSON I thought it better to point them out and let you (or somebody else) edit if appropriate. The first one is easy - a missing comma after the first SELECTed field; secondly you said to do a lateral join yet you didn't use the LATERAL keyword; thirdly I got an operator error on the final "=" character - is that because the final -> operators should be ->> operators?
@WayneIvory Thanks for the info! LATERAL is optional on set-returning functions iirc. And yes, json doesn't support equality, only jsonb does - casting to a string is easiest here indeed.

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.