I'm trying to do a query on a table where I want to select some columns and some other columns as a nested json object, for example, I want to select the list of users with it's address as a nested object.
SELECT
u.first_name, u.last_name, u.age, u.phone,
JSON_OBJECT(
'zip', a.zip,
'address', a.address,
'number', a.number,
'city', a.city,
'state', a.state
) as 'address'
FROM
tb_user u,
tb_user_address a
WHERE u.id_address = a.id
The expected result would be something like this:
[
{
first_name: 'my name',
last_name: 'my last name',
... // Some other fields
address: {
zip: '987',
address: 'street name',
... // Some other fields
}
},
{
// Another user
}
]
But when it returns, the address field is just a plain string, like this: address: "{'zip': '987', 'address': 'street name', 'city': 'cityname', 'state'...};" and only this field (the one using JSON_OBJECT) is returning like this, the others are ok.
When I return the result from the sql query, I'm doing like this:
$user_list = json_decode(json_encode($query_result), true);
But it also doesn't resolve the problem. Is there a way to turn that string into a valid json object?
SELECT JSON_OBJECT(...) as `address` FROM ...causes the fields inside theJSON_OBJECTcall to be converted to a JSON string and returned as theaddresscolumn. Your first name etc. aren't part of theJSON_OBJECTcall and as such won't be in there.JSON_OBJECTbefore, but you can just wrap the whole thing up in a json_object so you canjson_decodethe entire row that is returned:SELECT JSON_OBJECT(first_name, last_name, age, phone, JSON_OBJECT(<address fields)) FROM your table...Thenjson_decode($query_result)