简体   繁体   中英

Using JSON_TABLE to convert an ARRAY into Columns

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM