Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...