如何缩小JSON反应?

人气:137 发布:2023-01-03 标签: jquery javascript json minify

问题描述

您好,最近在一次面试中,我回答了这个问题。

如何缩小json响应

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

}

这就是问题所在。我不知道如何缩小,以及它背后的过程。有谁能解释一下吗?请

提前谢谢。

推荐答案

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

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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;

您必须在服务器端执行缩小操作才能改进响应大小。我想大多数语言都支持与上面的代码片段等同的代码。例如,在php中,用户可能会这样写(当然,如果您的服务器运行php):

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

$minified = json_encode(json_decode($myJson));

20