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.
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));
document.body.innerHTML = 'Result:<br>' + 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));