0

I have table like this:

 +----+-------+-------+--------------+ 
 | id | title | city  | street       |  
 +----+-------+-------+--------------+ 
 | 1  | First | London|  Oxford      |
 +----+-------+-------+--------------+ 
 |  2 | Second| Berlin| Nievenheimer |      
 +----+-------+-------+--------------+ 
 

Is here a way to write MySql query which will generate JSON output with nested elements. Similar like this:

{
  1: {
    "title": "First",
    "address": {
      "city": "London",
      "street": "Oxford"
    }
  },
  2: {
    "title": "Second",
    "address": {
      "city": "Berlin",
      "street": "Nievenheimer"
    }
  }
}
3
  • Why not post TEXT, when the image only contains text? Commented Nov 12, 2020 at 16:49
  • @Luuk I tried, but it after paste it was disorganized. Commented Nov 12, 2020 at 19:54
  • i do not see any disorganized things .... (see the edit) Commented Nov 12, 2020 at 20:01

1 Answer 1

2

You can use json generation functions:

select json_object_agg(
    id,
    json_object(
        'title',   title,
        'address', json_object('city', city, 'street', street)
    )
) res
from mytable
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.