我正在尝试解析服务器的json响应。我无法对服务器端做任何事情,因为它不能很快改变。
以下是他们的json响应:
{
prop[1][foo]: "foo number 1",
prop[1][bar]: "bar number 1",
prop[1][bazz]: "bazz number 1",
prop[2][foo]: "foo number 2",
prop[2][bar]: "bar number 2",
prop[2][bazz]: "bazz number 2"
}
现在我希望它像这样:
{
props: [
{foo: "foo number 1", bar: "bar number 1", bazz: "bazz number 1"},
{foo: "foo number 2", bar: "bar number 2", bazz: "bazz number 2"}
]
}
我该怎么做,我无法弄清楚如何迭代和设置。
我的尝试:
var temp = [];
var regExp = /\[([^)])\]/;
var matches;
_.each(element, function(value, key) {
if (key.indexOf('foo') >= 0) {
matches = regExp.exec(key);
temp[matches[1]] = value;
}
});
答案 0 :(得分:2)
我们可以进行字符串操作,因为在javascript中使用“eval()”是一个坏主意
var injson = '{prop[1][foo]: "foo number 1", prop[1][bar]: "bar number 1", prop[1][bazz]: "bazz number 1", prop[2][foo]: "foo number 2", prop[2][bar]: "bar number 2", prop[2][bazz]: "bazz number 2"}'
injson = injson.replace("{","");
injson = injson.replace("}","");
injson = injson.split("\",");
var outarr = [];
for(var index=0;index<injson.length;index++){
var _key = $.trim(injson[index].split(":")[0]);
var _value = $.trim(injson[index].split(":")[1]);
_value = _value.substring(1, _value.length-1);
var _index = parseInt(_key.substring(_key.indexOf("[")+1).substring(0,1));
var _prop = _key.substring(_key.indexOf("][")+2, _key.length-1);
if(!outarr[_index])
outarr[_index] = {};
outarr[_index][_prop] = _value;
};
console.log(outarr);
像这样的东西
如果您想使用eval,可以尝试减少for循环中的代码
答案 1 :(得分:1)
您可以使用 _.set(object, path, value)
,它将评估您为响应对象中的每个值设置的路径。
<强> DEMO 强>
<强>的Javascript 强>
void Reverse(node *&head) {
Reverse(head, head); //may want to rename or make private
}
如果您希望var data = {
"prop[1][foo]": "foo number 1",
"prop[1][bar]": "bar number 1",
"prop[1][bazz]": "bazz number 1",
"prop[2][foo]": "foo number 2",
"prop[2][bar]": "bar number 2",
"prop[2][bazz]": "bazz number 2"
};
function evaluate(data) {
var newData = {};
_.each(data, function(value, key) {
_.set(newData, key, value);
});
return definedItemsOnly(newData);
}
// Since the resulting value of the given data set above
// doesn't have prop[0] then this function below
// will provide you the means of removing any potential
// undefined values in an array or possibly undefined
// key values in an object.
function definedItemsOnly(item) {
var isDefined = _.negate(_.isUndefined);
if(_.isArray(item)) {
return _.filter(item, isDefined);
} else if(_.isObject(item)) {
return _(item).pick(isDefined).mapValues(definedItemsOnly).value();
}
return item;
}
console.log(evaluate(data));
回调采用更复杂的形式,则可以更改_.each
函数,如下所示:
evaluate()