3

I'm using mariaDB 10.3, I have a table:

CREATE TABLE user(id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, parameters longtext,  PRIMARY KEY(id));

With rows:

INSERT INTO user VALUES (1, 'name1', '{"number": 1, "text": "some text"}'), (2, 'name2', '{"number": 2, "text": "some more text"}');

I'm trying to write query that returns the table as JSON object. So far I have

SELECT CONCAT(
    '[',
      GROUP_CONCAT(JSON_OBJECT('id',id,'name',name,'parameters', parameters)),
    ']'
 ) 
FROM user;

But this returns:

[
  {"id": 1,
    "name": "name1",
    "parameters": "{\"number\": 1, \"text\": \"some text\"}"
  },
  {
    "id": 2,
    "name": "name2",
    "parameters": "{\"number\": 2, \"text\": \"some more text\"}"
  }
]

which is not a proper JSON. What should I change to get parameters properly formatted?

What I would like to get is:

[
  {
    "id": 1,
    "name": "name1",
    "parameters": {
      "number": 1,
      "text": "some text"
    }
  },
  {
    "id": 2,
    "name": "name2",
    "parameters": {
      "number": 2,
      "text": "some more text"
    }
  }
]

Thanks

4
  • (1) If you have just 1 row, what do you expect GROUP_CONCAT to accomplish? (2) Please add the desired result to your question. (Use Edit). Commented Dec 5, 2020 at 17:26
  • You are right, for simplicity I just showed 1 row, but 2 are minimum for this question to make sense. I also added desired result. Commented Dec 5, 2020 at 17:43
  • OK. Do I understand correctly that escaped parenthesize (\") is the only thing that separates you from success? Or have I missed something? Commented Dec 5, 2020 at 17:47
  • And additional quotation marks (") at the begging and at the end of the parameters entry. Commented Dec 5, 2020 at 17:53

2 Answers 2

1

Just JSON_COMPACT function, which's proper to MariaDB and does not exists in MySQL, might be applied for the parameters column

SELECT CONCAT(
       '[',
        GROUP_CONCAT(JSON_OBJECT('id',id,
                                 'name',name,'parameters', 
                                  JSON_COMPACT(parameters))),
       ']'
       ) AS "JSON Value"
  FROM user

Demo

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

2 Comments

Thanks, this does what i need.
you're welcome @friltase , welcome to contribution for SO too.
0

You can use JSON_OBJECT , JSON_ARRAYAGG(expr) concept to get your result. ref: https://www.tutorialspoint.com/mysql/mysql_aggregate_functions_json_arraygg.htm

I used this for one of my project work

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.