0

I have the following table of data

enter image description here

What I am trying to do is GROUP BY timestamp and JSON_MERGE the objects. What I expect as a result is the following.

enter image description here

I expected the following query to work but I just get an error

SELECT timestamp, JSON_MERGE(json)
FROM data
GROUP BY timestamp, JSON_MERGE(json)

The error I am getting is

Incorrect parameter count in the call to native function 'JSON_MERGE'

1 Answer 1

2

Assemble desired JSON using string functions and then cast it into JSON.

Example data

create table data (json json, timestamp datetime);

insert into data values
('{"a": 1}', '2016-10-01 00:00:00'),
('{"b": 2}', '2016-10-01 00:00:00'),
('{"c": 3}', '2016-10-01 11:11:11'),
('{}', '2016-10-01 11:11:11'),
('{"c": 33}', '2016-10-01 11:11:11');

Query to merge all json values grouped by timestamp

select cast(
  concat('{',  -- wrap everything in root object '{ ... }'
    group_concat(
      -- strip parenthesis from individual item representation
      -- '{"foo": 1}' -> '"foo": 1'
      substring(json, 2, length(json) - 2)),
  '}') as json) json,
timestamp
from data
-- skip empty JSON values to avoid getting extra comma during 
-- group_concat
where json != JSON_OBJECT()  
group by timestamp;

Query result

+------------------+---------------------+
| json             | timestamp           |
|------------------+---------------------|
| {"a": 1, "b": 2} | 2016-10-01 00:00:00 |
| {"c": 3}         | 2016-10-01 11:11:11 |
+------------------+---------------------+

Several caveats:

  • Behaviour of this snippet is different from JSON_MERGE(), for example:
    • When two or more properties have the same name their values are overwritten instead of being merged into array of values
    • It can't merge objects with arrays
  • Solution as presented only works with objects as a top level entity and not with arrays. It can be modified to work with arrays.
  • If relies on string representation of JSON objects beginning and ending with curly brackets {}. This might change in future versions of the server.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.