gpt4 book ai didi

javascript - 如何在javascript中将JSON解析为JSON?

转载 作者:行者123 更新时间:2023-11-28 13:13:55 24 4
gpt4 key购买 nike

太疯狂了,但我出于任何原因试图将 JSON 转换为 JSON。我有 json 并且我在 http://jsonlint.com 检查了 json,没关系。

{"d": "[{\"ID\":\"VN00000123\",\"NAME\":\"JOHN GREEN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"15-10-1987\"},{\"ID\":\"VN00000456\",\"NAME\":\"MERRY BLUE\",\"GENDER\":\"Female\",\"BIRTHDAY\":\"03-12-1983\"},{\"ID\":\"VN00000789\",\"NAME\":\"BLACK BROWN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"09-07-1990\"}]"}

现在,我需要像下面这样转换它

{
"columns": [
["ID"],
["NAME"],
["GENDER"],
["BIRTHDAY"]
],
"data": [
[
"VN00000123",
"JOHN GREEN",
"Male",
"15-10-1987"
],
[
"VN00000456",
"MERRY BLUE",
"Female",
"03-12-1983"
],
[
"VN00000789",
"BLACK BROWN",
"Male",
"09-07-1990"
]
]
}

有人对此有想法,请与我分享(使用 javascript 或 jquery)。非常感谢。

最佳答案

这个算法非常简单——像下面这样的算法应该可以工作:

function parse(a) {
//create object to return
var ret = {
columns: [],
data: []
};

//iterate the source array
a.forEach(function(item, i) {
if (i === 0) {
//first time through, build the columns
for (var key in item) {
ret.columns.push(key);
}
}

//now build your data item
ret.data[i] = [];

//use the column array to guarantee that the order of the fields in the source string doesn't matter
for (var j = 0; j < ret.columns.length; j++) {
var key = ret.columns[j];
ret.data[i].push(item[key]);
}
});
return ret;
}

var j = {
"d": "[{\"ID\":\"VN00000123\",\"NAME\":\"JOHN GREEN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"15-10-1987\"},{\"NAME\":\"MERRY BLUE\",\"BIRTHDAY\":\"03-12-1983\",\"ID\":\"VN00000456\",\"GENDER\":\"Female\"},{\"GENDER\":\"Male\",\"ID\":\"VN00000789\",\"NAME\":\"BLACK BROWN\",\"BIRTHDAY\":\"09-07-1990\"}]"
};

//j is an object with one property (d) that is a JSON string that needs parsing
var o = parse(JSON.parse(j.d));
console.log(o);

关于javascript - 如何在javascript中将JSON解析为JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40275543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com