简体   繁体   English

从 JSON 上的键和数组中提取值

[英]Extract Values from key and array on JSON

How could I extract the values in keys and array on json如何提取 json 上的键和数组中的值

json json

{
    "key1": "US",
    "key2": "545644566",
    "car": ["HONDA","TOYOTA","FORD"]
}

The resulted expected:结果预期:

key钥匙 value价值
key1键1 US我们
key2键2 545644566 545644566
car HONDA本田
car TOYOTA丰田
car FORD福特

I tried using:我尝试使用:

SELECT JSON_EXTRACT(u.json, CONCAT('$.','"',g.field_name,'"')),g.*
  FROM table_json u
  LEFT JOIN table_column g 
    ON JSON_CONTAINS(JSON_KEYS(u.json), JSON_QUOTE(g.field_name), '$')

You can use a dictionary table such as information_schema.tables along with iterating index values for some variables in order to generate rows for the elements of the arrays.您可以使用诸如information_schema.tables之类的字典表以及一些变量的迭代索引值,以便为 arrays 的元素生成行。 The following code also works for non-array elements without need of a conditional.以下代码也适用于不需要条件的非数组元素。 Apply JSON_KEYS() function to derive the key elements in the first subquery, and then use JSON_EXTRACT() for the respective indexes to derive the corresponding values of the arrays in the last subquery such as应用JSON_KEYS() function 导出第一个子查询中的关键元素,然后对各个索引使用JSON_EXTRACT()导出最后一个子查询中 arrays 的对应值如

WITH t1 AS
(
SELECT @i := @i + 1 AS i, 
       JSON_UNQUOTE(JSON_EXTRACT(kys, CONCAT('$[', @i - 1, ']'))) AS `key`,
       JSON_EXTRACT(json,
                         CONCAT('$.',
                                      JSON_EXTRACT(kys, CONCAT('$[', @i - 1, ']'))
                                      )
                        ) AS value, kys
  FROM t
  JOIN (SELECT @i := 0, JSON_KEYS(json) AS kys FROM t) AS k
  JOIN information_schema.tables
)
SELECT @k := IF(@j=`key`,@k + 1,0) AS `index`,
       @j := `key` AS `key`,
       JSON_UNQUOTE(JSON_EXTRACT(value, CONCAT('$[', @k, ']'))) AS value
  FROM t1
  JOIN (SELECT @k := 0 ) AS k
  LEFT JOIN information_schema.tables
    ON @k < JSON_LENGTH(value) - 1
 WHERE value IS NOT NULL 

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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