简体   繁体   中英

Unnest key value pairs from json object

I have a map with multiple key value pairs and I want to unnest them into separate rows.

"dayValueMap": {
    "2022-06-01": 1,
    "2022-06-02": 1,
    "2022-06-03": 1,
    "2022-06-04": 1,
    "2022-06-05": 1,
    "2022-06-06": 1,
}

I tried JSON_EXTRACT but that only extracts json from particular schema. Here I need to convert these key values as separate rows and in the map keys are dynamic.

Can someone help?

You can use the UNNEST() function in combination with JSON_EXTRACT() to unnest the key-value pairs of your map and convert them into separate rows in MySQL.

Here is an example of how you can use these functions:

SELECT 
    JSON_EXTRACT(dayValueMap, '$.*') as keyValuePairs
FROM 
    yourTable
UNNEST(keyValuePairs) as t(key, value)

My apologies, UNNEST() function is not a built-in function in MySQL, it's supported in other RDBMS like Bigquery, PostgresSQL, and Redshift.

If you want to achieve the same result as UNNEST in MySQL, you can use the following approach:

Using a self-join on a temporary table:

CREATE TEMPORARY TABLE temp_colors AS (SELECT id, color FROM items);
SELECT temp_colors.id, colors.color FROM temp_colors JOIN temp_colors AS colors ON temp_colors.id = colors.id;

Using a UNION ALL:

SELECT id, SUBSTRING_INDEX(SUBSTRING_INDEX(colors, ',', n), ',', -1) as color
FROM items
JOIN (
  SELECT 1 n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
  ) nums
ON LENGTH(colors) - LENGTH(REPLACE(colors, ',', '')) >= n-1

Using a procedure:

Create a stored procedure that accepts a string of comma separated values as input and returns a result set containing one row for each value in the string.

In MySQL 8.0 you can use:

  • JSON_KEYS : to extract the array of keys from " $.dayValueMap " path
  • JSON_TABLE : to generate a table containing your extracted keys, one per record
  • JSON_EXTRACT : to extract the value from your table, using the previously extracted keys
SELECT json_key, 
       JSON_EXTRACT(info, CONCAT('$.dayValueMap.', json_key)) AS json_value
FROM tab,
     JSON_TABLE(
         JSON_KEYS(info, '$.dayValueMap'), '$[*]' 
         COLUMNS(
             json_key JSON PATH '$'
         )
    ) t; 

Check the demo here .

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