这对你们中的一些人来说可能是一个简单的问题。但我只是不知道如何做到这一点,我非常需要帮助。这是我的 json:
{"name":"cust_num","comparison":"starts_with","value":"01"},
{"name":"cust_name","comparison":"starts_with","value":"ad"},
{"name":"cust_age","comparison":"=","value":"20"}
我的程序 JSON 警报如下所示:
{
"ID":"TBsKI7",
"dataType":"data",
"filters":[
"{\"name\":\"cust_num\",\"comparison\":\"starts_with\",\"value\":\"01\"}",
"{\"name\":\"cust_name\",\"comparison\":\"starts_with\",\"value\":\"ad\"}",
"{\"name\":\"cust_age\",\"comparison\":\"=\",\"value\":\"20\"}
],
"recordLimit":50,
"recordOffset":0,
.
.
.
}
这显然是一个错误。在我看来,第一个 json 被字符串化了两次(如果我使用这个术语是正确的)。现在,我想要的是如何纠正我的第一个 json,或者如何解析它,以便它输出时没有“\”。
我已经尝试使用 jQuery.parseJson() 但它返回 null。
感谢您的阅读。
编辑: 这是我的 javascript 代码,它生成上述 json:
$('#table tr').each(function(){
var td = '';
if ($(this).find("td:first").length > 0) { // used to skip table header (if there is)
$(this).find('option:selected').each(function(){
td = td + $(this).text()+ ',';
});
td = td + $(this).find('input').val();
filt[ctr]=td;
ctr += 1;
}
});
for (var i = 0;i<filt.length;i++) {
b = filt[i].split(',');
if (b[0] == "no"){
b[0] = "cust_num";
}
if (b[0] == "name"){
b[0] = "cust_name";
}
if (b[0] == "age"){
b[0] = "cust_age";
}
jsonobj.name = b[0];
jsonobj.comparison = b[1];
jsonobj.value = b[2];
c[i] = JSON.stringify(jsonobj); //if json.stringify, it will display the json with '\'
//if not, its only the last filter will be read for all the tr.
}
我有一个动态表,它将接受我将用来创建 json 的数据。
最佳答案
我希望你在某个地方定义你的变量。在 for 循环之外,你应该这样做
var c = [];
那就试试
c.push({
name: b[0],
comparison: b[1],
value: b[2]
});
而不是
jsonobj.name = b[0];
jsonobj.comparison = b[1];
jsonobj.value = b[2];
c[i] = JSON.stringify(jsonobj);
然后你应该能够做到
JSON.stringify(c);
关于javascript - 解析 json jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5946714/