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"
    }
  }
}
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Ramis
  • 13,985
  • 7
  • 81
  • 100

1 Answers1

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
GMB
  • 216,147
  • 25
  • 84
  • 135