无法解析 javascript 中的 json 字符串,这是 java 方法的响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19906912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to parse json String in javascript which is response of java method
提问by Swapnil Walivkar
Following is my controller which returns String
以下是我的控制器,它返回字符串
@RequestMapping("/hello1")
public @ResponseBody
String hello1() {
String jsonString = "[{\"deviceId\": \" e71b0be12218393e121cb728595af68995889fb9\",\"deviceName\": \" Xcaliber?s iPad3\",\"serialNumber\": \" DMPH9E74DJ8R\",\"modelNumber\": \" MC706\",\"productType\":\" iPad3,1\",\"deviceClass\": \" iPad\"},{\"deviceId\": \"\", \"deviceName\": \"\",\"serialNumber\": \"\",\"modelNumber\": \"\",\"productType\": \"\",\"deviceClass\": \"\"}]";
return jsonString;
}
I am getting this string as response in javascript. and I am trying follwing code in javascript
我在 javascript 中得到这个字符串作为响应。我正在尝试在 javascript 中执行以下代码
var deviceJsonDetails = $.parseJSON(response);
for(var count = 0;count < response.length; count++){
var id = count+1;
alert(deviceJsonDetails[count].deviceId);
$("#deviceId"+id).html(deviceJsonDetails[count].deviceId);
$("#deviceName"+id).html(deviceJsonDetails[count].deviceName);
$("#serialNumber"+id).html(deviceJsonDetails[count].serialNumber);
$("#modelNumber"+id).html(deviceJsonDetails[count].modelNumber);
}
But it is giving error on var deviceJsonDetails = $.parseJSON(response);
Error: SyntaxError: JSON.parse: expected property name or '}'
但它在var deviceJsonDetails = $.parseJSON(response);
Error: SyntaxError: JSON.parse: expected property name or '}'上给出错误
Can you please tell me where is the fault or any alternate solution to parse same string in js?
你能告诉我在 js 中解析相同字符串的错误或任何替代解决方案吗?
采纳答案by Sheetal
Check your JSON string in http://jsonlint.com/
在http://jsonlint.com/检查您的 JSON 字符串
The correct string that you need to parse should be: Remove the "\"
您需要解析的正确字符串应该是:删除“\”
[
{
"deviceId": "e71b0be12218393e121cb728595af68995889fb9",
"deviceName": "Xcaliber?siPad3",
"serialNumber": "DMPH9E74DJ8R",
"modelNumber": "MC706",
"productType": "iPad3,1",
"deviceClass": "iPad"
},
{
"deviceId": "",
"deviceName": "",
"serialNumber": "",
"modelNumber": "",
"productType": "",
"deviceClass": ""
}
]