我有一个像我下面给出的json数组
(?!^-)\D
这必须转换为
[
{"Name": {"xxx": [{"I": "FORENAME"} , {"I": "Surname"}]}},
{"EmailAddress":{"I": "yyy"}},
{"[ID]": {"I": "zzz"}},
{"[Company]": {"I": "aaa"}}
]
我可以使用地图功能
将单维json转换为数组[
["Name", ["xxx", [["I", "FORENAME"], ["I", "Surname"]]]],
["EmailAddress", ["I", "yyy"]],
["[ID]", ["I", "zzz"]],
["[Company]", ["I", "aaa"]]
]
但将其转换为具有多维度的工作很困难。是否有任何方法可以像这样转换json或任何解决方法..?
任何帮助都将受到高度赞赏。
答案 0 :(得分:4)
您可以将 $.map()
和 map()
与 recursion
var dimensions = [{
"Name": {
"xxx": [{
"I": "FORENAME"
}, {
"I": "Surname"
}]
}
}, {
"EmailAddress": {
"I": "yyy"
}
}, {
"[ID]": {
"I": "zzz"
}
}, {
"[Company]": {
"I": "aaa"
}
}];
function gen(data) {
// checking data is an object
if (typeof data == 'object') {
// checking it's an array
if (data instanceof Array)
// if array iterating over it
return data.map(function(v) {
// recursion
return gen(v);
});
else
// if it's an object then generating array from it
return $.map(data, function(value, index) {
// pushing array value with recursion
return [index, gen(value)];
});
}
// returning data if not an object
return data;
}
document.write('<pre>' + JSON.stringify(gen(dimensions), null, 3) + '</pre>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
答案 1 :(得分:2)
喜欢这个吗?
var oldOBJ = [
{"Name": {"xxx": [{"I": "FORENAME"} , {"I": "Surname"}]}},
{"EmailAddress":{"I": "yyy"}},
{"[ID]": {"I": "zzz"}},
{"[Company]": {"I": "aaa"}}
]
var newOBJ =JSON.parse(JSON.stringify(oldOBJ).replace(/\{/g,"[").replace(/\}/g,"]").replace(/:/g,","));
document.write(JSON.stringify(newOBJ));