如何从MySQL中提取JSON数组

时间:2017-11-28 00:14:50

标签: mysql json

我打算在我的数据库表中插入一个JSON数组用于动态目的。我在使用键/值对提取JSON对象时没有任何问题,但与JSON Arrays相反。见下面的例子:

[{"LCM": {"id": 333, "barcode": "ABC"}, "DCover": {"id": 444, "barcode": "CDE"}, "date_associated": "2017-11-27 23:59:59"}, {"LCM": {"id": 555, "barcode": "EFG"}, "DCover": {"id": 666, "barcode": "GHI"}, "date_associated": "2017-11-27 23:59:59"}, {"LCM": {"id": 777, "barcode": "IJK"}, "DCover": {"id": 888, "barcode": "KLM"}, "date_associated": "2017-11-27 23:59:59"}]

理想情况下,对于上面的每一个,如果被提取 - 它看起来像这样:

{"LCM": {"id": 777, "barcode": "IJK"}, "DCover": {"id": 888, "barcode": "KLM"}, "date_associated": "2017-11-27 23:59:59"}

现在的问题是,我如何能够如此提取它们:

1. {"LCM": {"id": 333, "barcode": "ABC"}, "DCover": {"id": 444, "barcode": "CDE"}, "date_associated": "2017-11-27 23:59:59"}
2. {"LCM": {"id": 555, "barcode": "EFG"}, "DCover": {"id": 666, "barcode": "GHI"}, "date_associated": "2017-11-27 23:59:59"}
3. {"LCM": {"id": 777, "barcode": "IJK"}, "DCover": {"id": 888, "barcode": "KLM"}, "date_associated": "2017-11-27 23:59:59"}

他们中的哪一个,我将能够根据需要解析,即:" $。LCM"或者" $。DCover.barcode"

JSON_EXTRACT(...)似乎只能通过定义特定JSON对象的键来获得。但这对于仅限于价值的JSON阵列(据我所知)而言并不适用

希望我能在这里得到一个提示。感谢。

1 个答案:

答案 0 :(得分:0)

如果您使用的是MySQL> = 8.0.4,则可以使用JSON_TABLE

查询示例

with tbl(val) as (
  select CAST('[{"LCM": {"id": 333, "barcode": "ABC"}, "DCover": {"id": 444, "barcode": "CDE"}, "date_associated": "2017-11-27 23:59:59"}, {"LCM": {"id": 555, "barcode": "EFG"}, "DCover": {"id": 666, "barcode": "GHI"}, "date_associated": "2017-11-27 23:59:59"}, {"LCM": {"id": 777, "barcode": "IJK"}, "DCover": {"id": 888, "barcode": "KLM"}, "date_associated": "2017-11-27 23:59:59"}]'
  as json
 )
)
select rowid, content from tbl, JSON_TABLE(val, '$[*]' columns (rowid for ordinality, content json PATH '$')) as jt;

结果

+-------+---------------------------------------------------------------------------------------------------------------------------+
| rowid | content                                                                                                                   |
+-------+---------------------------------------------------------------------------------------------------------------------------+
|     1 | {"LCM": {"id": 333, "barcode": "ABC"}, "DCover": {"id": 444, "barcode": "CDE"}, "date_associated": "2017-11-27 23:59:59"} |
|     2 | {"LCM": {"id": 555, "barcode": "EFG"}, "DCover": {"id": 666, "barcode": "GHI"}, "date_associated": "2017-11-27 23:59:59"} |
|     3 | {"LCM": {"id": 777, "barcode": "IJK"}, "DCover": {"id": 888, "barcode": "KLM"}, "date_associated": "2017-11-27 23:59:59"} |
+-------+---------------------------------------------------------------------------------------------------------------------------+