0

I want to select rows information from table in MySQL. Rather than getting as it is, I want to get this information as JSON array list type.

For example,

A   B   C
=========
1   2   3 
2   3   4

I want it to become data like the followings.

{ rows: [ 
            { "A" :  1, "B" : 2, "C" : 3}, 
            { "A" :  2, "B" : 3, "C" : 4}
]}
2
  • Why wouldn't you do this in application code? Commented Jan 30, 2018 at 9:22
  • @Strawberry I thought this function may be provided by MySQL itself and it is gonna be good function whenever I want to test REST APIs with json data. Commented Jan 30, 2018 at 9:24

1 Answer 1

1

In MySQL you can achieve as below:

SELECT CONCAT('{ rows:[', result, ']}') AS result1 FROM
(
SELECT GROUP_CONCAT('{', jsondata, '}' SEPARATOR ',') AS result FROM
(
  SELECT 
    CONCAT
    (
      '"A":'   , A  , ',' 
      '"B":', B, ','
      '"C":'  , C
    ) AS jsondata
  FROM test
) AS jsondata
) AS jsonsdata1;

SQL Demo link: http://sqlfiddle.com/#!9/95bbbc/2

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

2 Comments

Thanks for sharing your code and help. Is this only way to do this? In this way, I should write every columns and data by myself. I have many tables with tons of columns.
You can also convert this at the server side like C#, PHP. It would be easy

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.