A sql query returns many rows of the following simple structure:
“name”, id
I need to provide it in JSON format. I assume the proper format is an array of the simple structures as seen below. Although I’m not sure if there is a less verbose structure that would be preferable. for example, should I avoid the repeating name/id field names somehow to reduce size?
[
{
"name": "greg",
"id": 13
},
{
"name": "greg",
"id": 12
},
{
"name": "greg",
"id": 11
}
]
Here is the php i use to generate the json:
$rows = array();
while($r = $result->fetch_assoc())
{
$rows[] = $r;
}
echo json_encode($rows, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
You could serve it in the form of a 2d array, but I don’t think it makes much of a difference.
Simple example to make that happen:
Which would give you an array grouped by names.
Also, seeing as this output is sent to the browser, it should be minified.
The user doesn’t (at least, doesn’t need to) see the actual JSON report, it is used by his browser as JavaScript variables.
Because of that, there’s no benefit in providing a prettified version, plus, you’re bloating the content length and use more bandwidth.
Bottom Line: Server JSON as compressed and minified as possible.