Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify json response?

Hi recently in one of the interview i gone through this question.

How to minify json response

    {
name: "sample name",
product: "sample product",
address: "sample address"

}

this what the question. I dont know how to minify and the process behind it. Can any one explain? please

Thanks in Advance.

like image 347
Vignesh Avatar asked Jan 28 '18 14:01

Vignesh


People also ask

Can you minify JSON?

Users can also minify the JSON file by uploading the file. Once you have minified JSON Data. User can download it as a file or save it as a link and Share it. JSON Minifier works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

Why do we minify JSON?

The purpose of the JSON Minifier tool is to minify JSON text, reduce your JSON file size and make it hard to read. JSON (JavaScript Object Notation) is a lightweight data-interchange format, it's useful for exchanging data from client to server, or from server to client.

How do you minify JSON in VS code?

Ctrl(Cmd)+Alt+M for JSON pretty. Alt+M for JSON minify.

How do I minify JSON in Intellij?

Format JSON, Minify JSON, Verify JSON as if you editing a file with . json suffix. Usage: Paste JSON string into editor, and press Reformat Code (Ctrl + Alt + L in windows) to format code as if you editing a file with . json suffix.


2 Answers

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));
like image 70
JJWesterkamp Avatar answered Oct 16 '22 04:10

JJWesterkamp


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.

like image 27
Jonathan Avatar answered Oct 16 '22 02:10

Jonathan