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

前端 未结 4 2139
暖寄归人
暖寄归人 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:02

    You don't use JSON_EXTRACT(). You use JSON_TABLE():

    mysql> create table mytable ( id serial primary key, data json);
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> insert into mytable 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?"}]';
    Query OK, 1 row affected (0.00 sec)
    
    mysql> SELECT j.* FROM mytable,
      JSON_TABLE(data, '$[*]' COLUMNS (
        name VARCHAR(20) PATH '$.name', 
        label VARCHAR(50) PATH '$.label'
      )) AS j;
    +------------+-------------------+
    | name       | label             |
    +------------+-------------------+
    | question-1 | Enter your name?  |
    | question-2 | Enter your email? |
    | question-3 | Enter your city?  |
    +------------+-------------------+
    

    JSON_TABLE() requires MySQL 8.0.4 or later. If you aren't running at least that version, you will have to upgrade.

    Honestly, if you need to access the individual fields, it's less work to store your data in normal columns, and avoid using JSON.

提交回复
热议问题