mysql 动态sql 解析json,如何从MySQL中的动态键值对JSON提取?

I have the user table with user_id and user_details. it contains the JSON data in string format as shown below:

[{"name":"question-1","value":"sachin","label":"Enter your name?"},

{"name":"question-2","value":"abc@example.com","label":"Enter your email?"},

{"name":"question-3","value":"xyz","label":"Enter your city?"}]

I have tried with the json_extract but it return the result if json has data as shown below:

{"name":"question-1","value":"sachin","label":"Enter your name?"}

then it return the result as,

Name | Label

question-1 | Enter your name?

Expected Result :

I want to extract all name and label from json in sql query.

Example-1:

Consider that we have the following data in user_details column,

[{"name":"question-1","value":"sachin","label":"Enter your name?"},

{"name":"question-2","value":"abc@example.com","label":"Enter your email?"},

{"name":"question-3","value":"xyz","label":"Enter your city?"}]

then the sql query should return the result in following format ,

Name | Label

question-1 | Enter your name?

question-2 | Enter your email?

question-3 | Enter your city?

How to get this using JSON_EXTRACT in MySQL?

解决方案

I assume that you are not using a table.

SET @data = '[{"name":"question-1","value":"sachin","label":"Enter your name?"},

{"name":"question-2","value":"abc@example.com","label":"Enter your email?"},

{"name":"question-3","value":"xyz","label":"Enter your city?"}]';

SELECT JSON_EXTRACT(@data,'$[*].name') AS "name", JSON_EXTRACT(@data,'$[*].label') AS "label";

it will return

name | label

["question-1", "question-2", "question-3"] | ["Enter your name?", "Enter your email?", "Enter your city?"]

SQL should be like below according to your table and column name:

SELECT JSON_EXTRACT(user_details,'$[*].name') AS "name", JSON_EXTRACT(user_details,'$[*].label') AS "label" FROM user;

you can match them by using some loops for arrays. I do not know if this is the best way but it satisfy my needs.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值