1

I have table:

 -------+-------
| param | value |
|-------+-------|
|     A |  200.5|
|     B |   70.2|
 ---------------

When I execute:

select json_object(`param`, `value`) from `table`

I'm getting this:

{"A": "200.5"}
{"B": "70.2"}

But I want this:

{
 "A": "200.5",
 "B": "70.2"
}

2 Answers 2

3

You can use json aggregate function json_objectagg(), available since MySQL 5.7:

select json_objectagg(param, value) js from mytable

Demo on DB Fiddle:

| js                      |
| :---------------------- |
| {"A": 200.5, "B": 70.2} |

On earlier versions, where json aggregate functions are not available, you could do string concatenation:

select concat('{', group_concat('"', param, '": ', value separator ', '), '}') js
from mytable

Demo on DB Fiddle

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

2 Comments

Thank you again GMB, but the server which I use is 5.5 ;-(
@iMarh: I updated my answer with a solution for earlier versions.
0

I assume you wan't to get this result directly from the MySQL server, if that's the case, the closest to an answer comes this How to convert result table to JSON array in MySQL.

If you're ok with getting the results further down the line you can always parse it using a language of your choice.

Hope that helps.

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.