Unable to parse json String in javascript which is response of java method

19,069

Check your JSON string in http://jsonlint.com/

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": ""
    }
]
Share:
19,069
Swapnil Walivkar
Author by

Swapnil Walivkar

Updated on June 14, 2022

Comments

  • Swapnil Walivkar
    Swapnil Walivkar almost 2 years

    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

    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 '}'

    Can you please tell me where is the fault or any alternate solution to parse same string in js?

  • Nils
    Nils over 10 years
    the JSON string is in double quotes that's why \ is used only to escape ".
  • Sheetal
    Sheetal over 10 years
    after you return the string and before your parse can you remove "\"