Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

sql - Combine two json array as key-value in mysql and create one json object

I have two JSON array fields in MySQL like this:

["a", "b", "c"]
["apple", "banana", "coconut"]

Now I want to combine them into one JSON object like this:

{"a":"apple", "b":"banana", "c":"coconut"}

Is there any MySQL function for this?

question from:https://stackoverflow.com/questions/65642272/combine-two-json-array-as-key-value-in-mysql-and-create-one-json-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would approach this in a simple way.

  • Unnest the two JSON structures using JSON_TABLE().
  • Join the two tables together.
  • Construct the appropriate JSON objects and aggregate.

The following implements this logic. The first CTE extracts the keys. The second extracts the values, and finally these are combined:

WITH the_keys as (
      SELECT j.*
      FROM t CROSS JOIN
           JSON_TABLE(t.jsdata1,
                      '$[*]'
                      columns (seqnum for ordinality, the_key varchar(255) path '$')
                     ) j
     ),
     the_values as (
      SELECT j.*
      FROM t CROSS JOIN
           JSON_TABLE(t.jsdata2,
                      '$[*]'
                      columns (seqnum for ordinality, val varchar(255) path '$')
                     ) j
     )
select json_objectagg(the_keys.the_key, the_values.val)
from the_keys join
     the_values
     on the_keys.seqnum = the_values.seqnum;

Here is a db<>fiddle.

Note that this is quite generalizable (you can add more elements to the rows). You can readily adjust it to return multiple rows of data, if you you have key/value pairs on different rows, and it uses no deprecated functionality.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...