0

I've been attempting to use MySQL 8's JSON_TABLE to extract the root keys and then their nested values. The problem is the root keys are dynamic and the nested key/value pairs might not exist.

JSON:

{
  "Foo": {
    "A": 3
  },
  "Bar": {
    "A": 1,
    "B": 368
  },
  "Biz": {
    "C": 2,
    "D": 10
  }
}

In this JSON the root keys "Foo", "Bar", and "Biz" are dynamic and for each of their objects I want to extract the "A" key's value, which may or may not exist. For example, the above code would return this result set:

json_key a_value
Foo 3
Bar 1
Biz null

I've been something along these lines but no luck (just returns one row of nulls):

select * from json_table('{"Foo": {"A": 3}, "Bar": {"A": 1, "B": 368}, "Biz": {"C": 2}}', 
    '$' COLUMNS(
        json_key varchar(255) path '$.*',
        sub_value integer path '$.*.A'
    )
) as i;

In the worst case I can try to restructure the JSON but it's already in the database so I'm hoping to leverage MySQL's JSON capability. Any ideas?

1 Answer 1

1
SELECT json_key,
       JSON_EXTRACT(@json_value, CONCAT('$.', json_key, '.A')) a_value
FROM JSON_TABLE(JSON_KEYS(@json_value),
                '$[*]' COLUMNS (json_key VARCHAR(255) PATH '$')) keystable

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=dd9c01e77d57206d587dd2d17340bc02

Sign up to request clarification or add additional context in comments.

1 Comment

That works! Thank you. I've been fighting this for hours.

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.