如何缩小json响应?

Vig*_*esh 8 javascript jquery json minify

嗨,最近在一次采访中,我回答了这个问题。

如何缩小json响应

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

}
Run Code Online (Sandbox Code Playgroud)

这有什么问题。我不知道如何缩小及其背后的过程。谁能解释一下?请

提前致谢。

Jef*_*amp 11

您可以解析 JSON,然后立即重新序列化解析的对象:

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;
Run Code Online (Sandbox Code Playgroud)

您必须执行缩小服务器端才能改善响应大小。我想大多数语言都支持与上述代码段等效的内容。例如,在 php 中可以这样写(当然,如果您的服务器运行 php):

$myJson = '{
    "name": "sample name",
    "product": "sample product",
    "address": "sample address" 
}';

$minified = json_encode(json_decode($myJson));
Run Code Online (Sandbox Code Playgroud)