0

In MySQL, I am trying to create a JSON_OBJECT from rows of data containing key-value pairs.

Here is the sample data:

CREATE TABLE TempValuePair( MyKey VARCHAR(64), MyValue VARCHAR(64) );
INSERT INTO TempValuePair VALUE 
    ('Country', 'Argentina'), 
    ('Capital', 'Buenos Aires'), 
    ('Population', 45810000 );

The following statement seems to return an argument that conforms to the JSON_OBJECT requirements:

SELECT GROUP_CONCAT( 
    CONCAT( '\'', MyKey, '\',\'', Myvalue, '\'' ) 
    ORDER BY MyKey 
) 
FROM TempValuePair;

However, the following statement fails:

    SELECT GROUP_CONCAT( 
        CONCAT( '\'', MyKey, '\',\'', Myvalue, '\'' ) 
        ORDER BY MyKey 
    ) 
    FROM TempValuePair 
);

Any advice about what I am doing wrong would be greatly appreciated. Thanks!

1 Answer 1

2

You seem to want json_objectagg, which is available in MySQL since version 5.7. The function aggregates key/value pairs from multiple rows into a single JSON object:

select json_objectagg(mykey, myvalue) as js from TempValuePair;

Yields:

{"Capital": "Buenos Aires", "Country": "Argentina", "Population": "45810000"}

Demo on DB Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I needed to learn - thank you very much for your help !

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.