How to JSON extract from dynamic key value pair in MySQL?

前端 未结 4 2085
暖寄归人
暖寄归人 2021-01-25 22:40

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\",\"         


        
4条回答
  •  不知归路
    2021-01-25 23:04

    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.

提交回复
热议问题