如何解析json字符串并迭代json对象

时间:2015-01-31 15:35:17

标签: javascript jquery json

我向服务器发出了一个ajax请求并从json string中获取响应。当我去JSON.stringify时,它有很多空白响应。当我尝试解析json对象时收到的错误消息 SyntaxError:JSON.parse:JSON数据第1行第1列的意外字符

以下是示例代码:

$.post("http://example.com/index.cfm?fuseaction=shopping.admin&stamps=getStampsRates&Order_No="+order_id+"&stamps_service_type="+selectedServiceType+"",function(data,status)
       {
           if(status=="success")
           {
               var data=JSON.parse(data);
               //original resonse aspected  from server     
               //   var json ='[{"PACKAGETYPE":"Postcard","AMOUNT":0.34},{"PACKAGETYPE":"Letter","AMOUNT":0.48},{"PACKAGETYPE":"Large Envelope or Flat","AMOUNT":0.98},{"PACKAGETYPE":"Thick Envelope","AMOUNT":1.93},{"PACKAGETYPE":"Package","AMOUNT":1.93},{"PACKAGETYPE":"Large Package","AMOUNT":1.93}] ';
               $.each(data, function(idx, obj) {
                   alert(obj.PACKAGETYPE);
               });
           }
       });

我做了一些更改然后尝试解析:

var data=JSON.stringify(data);
var newJ= JSON.parse(data);
alert("newJ:"+JSON.stringify(newJ));

并获得以下共鸣:

 "\r\n\r\n\t\r\n[{\"PACKAGETYPE\":\"Large Envelope or Flat\",\"AMOUNT\":2.69},{\"PACKAGETYPE\":\"Thick Envelope\",\"AMOUNT\":2.69},{\"PACKAGETYPE\":\"Package\",\"AMOUNT\":2.69},{\"PACKAGETYPE\":\"Large Package\",\"AMOUNT\":2.69}]\r\n\t\r\n\r\n"

尝试迭代上面的json对象获取错误 TypeError:t未定义

请帮我解决上述问题。

由于

1 个答案:

答案 0 :(得分:1)

我认为你的问题可能很复杂。首先,在相同的范围内,您有两个数据'由于参考问题,可能会覆盖原始响应。另一个像@adeneo说的那样,json在服务器端出现了畸形。所以试着改变这个。 我创建了一个JSFiddle来解析你的JSON响应的两个版本,因为我们根据你的帖子确切地不确定数据响应的样子。

JSFiddle

上的代码示例
var json ='[{"PACKAGETYPE":"Postcard","AMOUNT":0.34},{"PACKAGETYPE":"Letter","AMOUNT":0.48},{"PACKAGETYPE":"Large Envelope or Flat","AMOUNT":0.98},{"PACKAGETYPE":"Thick Envelope","AMOUNT":1.93},{"PACKAGETYPE":"Package","AMOUNT":1.93},{"PACKAGETYPE":"Large Package","AMOUNT":1.93}]';

var json1 = '"\r\n\r\n\t\r\n[{\"PACKAGETYPE\":\"Large Envelope or Flat\",\"AMOUNT\":2.69},{\"PACKAGETYPE\":\"Thick Envelope\",\"AMOUNT\":2.69},{\"PACKAGETYPE\":\"Package\",\"AMOUNT\":2.69},{\"PACKAGETYPE\":\"Large Package\",\"AMOUNT\":2.69}]\r\n\t\r\n\r\n"'

var obj = JSON.parse(json);
$.each(obj, function(i, item) {
    console.log(obj[i].PACKAGETYPE);
});

json1 = json1.split('[')[1].split(']')[0].replace('\\','');
json1 = '[' + json1 + ']';
console.log(json1);
var obj = JSON.parse(json1);
$.each(obj, function(i, item) {
    console.log(obj[i].PACKAGETYPE);
});