Reputation: 425
I recently got the following question in an interview.
How would you minify a JSON response?
{
name: "sample name",
product: "sample product",
address: "sample address"
}
I don't know how to minify JSON and the implementation behind it. Can anyone please explain?
Thank you.
Upvotes: 20
Views: 37568
Reputation: 7916
You can parse the JSON and then immediately re-serialize the parsed object:
var myJson = `{
"name": "sample name",
"product": "sample product",
"address": "sample address"
}`;
// 'Minifying' the JSON string is most easily achieved using the built-in
// functions in the JSON namespace:
var minified = JSON.stringify(JSON.parse(myJson));
console.log(minified);
You'll have to perform the minification server-side to get an improvement in response size. I suppose most languages support an equivalent to the above snippet. For example, in php one might write this (if your server runs php, of course):
$myJson = '{
"name": "sample name",
"product": "sample product",
"address": "sample address"
}';
$minified = json_encode(json_decode($myJson));
Upvotes: 25
Reputation: 1339
Another method could be to create it as a array with implicit keys - basically the first item in the array maps to key 'name', the second to 'product' etc - this requires both sender and receiver of the message to know exactly the order of keys, so in your example it could be reduced to
["sample name","sample product","sample address"]
you can't really make it much shorter than that. If you have complex objects with sub keys you can use nested multidimensional arrays eg.
["sample name","sample product",["sample address1","sample address2"]]
This would be a good option for things like multiplayer game server networking where message size is a major factor for reducing latency and the client and server both know how the message is structured.
It's not strictly Json, but sometimes you have to use pragmatic solutions for performance.
Upvotes: 2
Reputation: 9151
The obvious way would be to strip the whitespace. Beside that you could also map the keys to something shorter like a, b, c.
Also if you want to be a jerk about it; you could tell them that valid json would have quotes around the keys. This seems to be a js object, not json.
Upvotes: 3