[英]Create JSON object from complex string array
I have been given these test inputs that need to be parsed into a JSON object organized by their Key split by an underscore. 这些测试输入已被提供给我,这些输入需要解析为JSON对象,该对象按其Key(下划线)分割。
var testInput1 = '{"Data_Structure_Test1": "Test1 Data"}';
var testInput2 = '{"Data_Structure_Test2": "Test2 Data"}';
var testInput3 = '{"Data_Structure_Test3": "Test3 Data"}';
var testInput4 = '{"Data_AnotherStructure": "AnotherStructure Data"}';
var testInput5 = '{"Data_JustAnother": "JustAnother Data"}';
var testInput6 = '{"NewData_NewTest": "NewTest Data"}';
So the above testInputs
should spit out: 因此,上面的testInputs
应该吐出来:
{
"Data": {
"Structure": {
"Test1": "Test1 Data",
"Test2": "Test2 Data",
"Test3": "Test3 Data"
},
"AnotherStructure": "AnotherStructure Data",
"JustAnother": "JustAnother Data"
},
"NewData": {
"NewTest": "NewTest Data"
}
}
I can't seem to get the JSON objects to collect into the correct container. 我似乎无法将JSON对象收集到正确的容器中。
Here is a JSFiddle that I have been using to test with 这是我一直用来测试的JSFiddle
Here is my function that I am calling to parse the string 这是我要解析字符串的函数
function parse_input(aInput) {
let jObj = JSON.parse(aInput);
for (let key in jObj) {
let objKeys = key.split("_");
for (i = 0; i < objKeys.length; i++) {
if (data.hasOwnProperty(objKeys[i])) {
data[key] = jObj[key];
} else {
data[objKeys[i]] = jObj[key];
}
}
And how I am passing in the inputs: 以及我如何传递输入:
var data = {};
parse_input(testInput1);
parse_input(testInput2);
parse_input(testInput3);
parse_input(testInput4);
parse_input(testInput5);
parse_input(testInput6);
var result = JSON.stringify(data, undefined, '\t');
Can anyone see what I am doing wrong? 谁能看到我在做什么错?
I do have access the jQuery
framework if that will make this any easier. 我确实可以访问jQuery
框架,如果这样做会更容易。
function parse_input(json){
const obj = JSON.parse(json);
for(const key in obj){
const keys = key.split("_");
keys.slice(0,-1).reduce(function(obj, key){
return obj[key] || (obj[key] = {});
}, data)[keys.pop()] = obj[key];
}
}
You may want to use reduce to go deep into the data object. 您可能需要使用reduce来深入数据对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.