javascript - 解析 json jquery

标签 javascript jquery json

这对你们中的一些人来说可能是一个简单的问题。但我只是不知道如何做到这一点,我非常需要帮助。这是我的 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/

相关文章:

javascript - 类型错误 : c[a] is undefined in CKEditor

json - N1QL 数组查询 where 条件检查内部元素

c# - 读取 .NET 6 API 中的 appsettings.{env}.json 对象 - 值为 NULL

javascript - 在回调函数范围之外访问来自 chrome.tabs.query 的信息

javascript - Java应用程序根据用户过滤条件从数据库中提取数据

javascript - 如何缩小html容器中的图像

jQuery UI 选项卡没有 href 和/或内容,只有事件?

javascript - JQuery 插件,Javascript - 如何仅为 JQuery 插件全局变量或 json 对象创建并在函数级别更改此(变量、对象)

php - 在两个表单之间传递值

javascript - 计算两个时间范围数组的并集时间范围(带有矩范围)