javascript 将 JSON 对象转换为另一个对象 - 格式化它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9016546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:20:19  来源:igfitidea点击:

Transform JSON Object to another - Format It

javascript

提问by Sascha Heim

i want to transform a json formated output to another. How i can do this ?

我想将一个 json 格式的输出转换为另一个。我怎么能做到这一点?

Example: Old json

示例:旧的 json

"data": 
[
    {
        "id" : "e49e183e-9325-4e62-8eda-7e63fb7cdbbd",
        "name" : "test"
    },
    {
        "id" : "ac310894-d808-447b-a189-d07edb7f6dd7",
        "name" : "test2"
    }
]

New Json which i want without braces only like this with bracket

我想要的没有大括号的新 Json 只是像这样带括号

"aaData": 
[ 
    [
        "e49e183e-9325-4e62-8eda-7e63fb7cdbbd","test"
    ],
    [
        "ac310894-d808-447b-a189-d07edb7f6dd7","test2"
    ]
] 

回答by Niklas

You could just loop through the items and push them into a new object:

您可以循环遍历这些项目并将它们推送到一个新对象中:

var len = old.data.length,
    newData = {aaData:[]},
    i;

for ( i=0; i < len; i+=1 ) {
    newData.aaData.push( [ old.data[ i ].id, old.data[ i ].name] );   
}

example: https://jsfiddle.net/q2Jzb/1/

示例:https: //jsfiddle.net/q2Jzb/1/

You are presumably passing these to DataTables (as you use the name aaData), note that DataTables takes an object as the configuration, it's not the same as JSON.

您可能将这些传递给 DataTables(因为您使用名称 aaData),请注意 DataTables将对象作为配置,它与 JSON 不同。

回答by Matt

Try the following;

尝试以下操作;

function format(oldFormat) {
    var newFormat = [];

    oldFormat = oldFormat.data;

    for (var i=0;i<oldFormat.length;i++) {
        newFormat.push([oldFormat[i].id], oldFormat[i].name);
    };

    return {
        aaData: newFormat
    };
}

You'd then call use the function by;

然后,您可以通过以下方式调用使用该函数;

var newStuff = format(varPointingToOldStuff);

The function expects to receive a JavaScript object rather than JSON, and returns a JavaScript object rather than JSON. Make sure you understand the differences between a JSON (string) and a JavaScript object.

该函数期望接收一个 JavaScript 对象而不是 JSON,并返回一个 JavaScript 对象而不是 JSON。确保您了解 JSON(字符串)和 JavaScript 对象之间的区别

You can convert a JSON string to a JavaScript object using JSON.parse(yourJsonString), and can convert a JavaScript object to a JSON string using JSON.stringify(yourJavaScriptObject).

您可以使用 将 JSON 字符串转换为 JavaScript 对象JSON.parse(yourJsonString),也可以使用 将 JavaScript 对象转换为 JSON 字符串JSON.stringify(yourJavaScriptObject)

回答by nnnnnn

You could just do it as a string replace:

您可以将其作为字符串替换:

newJSON = oldJSON.replace(/"id" : |"name" : /g, "")
                 .replace(/{/g, "[").replace(/}/g, "]");

But that's kind of dodgy. The other way is to parse the JSON and then process the resulting object and then turn the result back into JSON:

但这有点狡猾。另一种方法是解析 JSON,然后处理结果对象,然后将结果转回 JSON:

var oldData = JSON.parse(oldJSON)["data"],
    aaData = [],
    arr,
    newJSON,
    i, k;

for (i = 0; i < data.length; i++) {
    arr = [];
    for (k in data[i])
       arr.push(data[i][k]);
    aaData.push(arr);
}

newJSON = JSON.stringify({ "aaData" : aaData });

Where oldJSONis the string with the old format from your question. (I've just looped through the properties in each array item rather than assuming they'll always have "id" and "name" properties.)

oldJSON您的问题中旧格式的字符串在哪里。(我只是遍历了每个数组项中的属性,而不是假设它们总是具有“id”和“name”属性。)

回答by Andrew Sklyarevsky

You can use JavaScript to transform the input data into a new form of object and then use JSON JavaScript library (the JSON.stringify function, see more here http://www.json.org/js.html) to convert the newly created object into a proper JSON. The following code uses jQuery and the JSON library to solve your problem. Use of jQuery is purely optional, as well as there are other libraries to make JSON.

您可以使用 JavaScript 将输入数据转换为新形式的对象,然后使用 JSON JavaScript 库(JSON.stringify 函数,在此处查看更多信息http://www.json.org/js.html)来转换新创建的对象对象转换为适当的 JSON。以下代码使用 jQuery 和 JSON 库来解决您的问题。jQuery 的使用完全是可选的,还有其他库可以生成 JSON。

<pre id="code"></pre>

<script type="text/javascript">
    $(document).ready(function () {
        var old = { "data":
            [
                {
                    "id": "e49e183e-9325-4e62-8eda-7e63fb7cdbbd",
                    "name": "test"
                },
                {
                    "id": "ac310894-d808-447b-a189-d07edb7f6dd7",
                    "name": "test2"
                }
            ]
        };

        var newData = [];
        for (var i = 0, l = old.data.length; i < l; i++) {
            var o = old.data[i];
            newData[i] = [o.id, o.name];
        }
        $("#code").text(JSON.stringify(newData));
    });
</script>

回答by Anu

You can also use JSON Path and use the query ($..id) on your dataset yields exactly what you seem to be looking for. Checkout https://jsonpath.com/? and enter your data in the left hand box and $..id in the text box for JSONPath Syntax

您还可以使用 JSON Path 并在您的数据集上使用查询 ($..id) 产生您似乎正在寻找的内容。结帐https://jsonpath.com/?并在左侧框中输入您的数据,并在 JSONPath 语法的文本框中输入 $..id