0

I have a database column (named "details") formatted as a JSON object that contains the following data:

'{"300-000012": {"is_complete": "False", "is_in_progress": "True"}, 
  "300-000018": {"is_complete": "True", "is_in_progress": "False"}}'

I can't seem to convert the Array into Columns. I've tried

SELECT mh.*, jt.*
FROM history AS mh,
JSON_TABLE (mh.details, '$[*]' 
    COLUMNS (
        NESTED PATH '$.*' COLUMNS (jt_complete VARCHAR(255) PATH '$.is_complete'),
        NESTED PATH '$.*' COLUMNS (jt_progress VARCHAR(255) PATH '$.is_in_progress')
        )
        ) AS jt)

But I get an Error Code

Error Code: 3143. Invalid JSON path expression

Ideally I would get something like:

  details             jt_complete            jt_progress
  300-000012             FALSE                  TRUE
  300-000018              TRUE                  FALSE

Any help would be appreciated. Thx

2
  • 2
    Out of curiosity, why are you storing the data in JSON if you want them in individual columns? Commented Nov 20, 2020 at 0:32
  • We store all the information in a JSON object so it is in 1 row but then we need to break out the JSON object when we want to utilize the data. LMK if that makes sense. Commented Nov 27, 2020 at 4:18

1 Answer 1

1

This is a tricky one because the keys of the object are variable. This means you need to extract the keys and the values separately for each object. The values can be connected by using an ordinality column for each JSON_TABLE and joining them on that:

SELECT mh.id, jk.details, jt.jt_complete, jt.jt_progress
FROM history mh
JOIN JSON_TABLE(
  JSON_KEYS(mh.details),
  '$[*]' COLUMNS (
    rn FOR ORDINALITY,
    details VARCHAR(10) PATH '$'
  )
) jk
JOIN JSON_TABLE(
  JSON_EXTRACT(mh.details, '$.*'),
  '$[*]' COLUMNS (
    rn FOR ORDINALITY,
    jt_complete VARCHAR(10) PATH '$.is_complete',
    jt_progress VARCHAR(10) PATH '$.is_in_progress'
  )
) jt ON jt.rn = jk.rn

Demo on dbfiddle

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

2 Comments

As a follow-on to this question - is it possible to return the Value JSON object as a single object (ie not broken apart)? ie details: 300-000012 and value: {"is_complete": "False", "is_in_progress": "True"} ?
@PrashantMarathay sure, you can put it together using JSON_OBJECT. See for example dbfiddle.uk/gILW18NN

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.