2

I have a Piece of code in JS to loop a JSON using Jquery each function. it's showing error as length is null or not an object.

var  claimJSONString = '{"claimJSON": [' + jsonString + ']}';
    //alert(claimJSONString);
      J.each(claimJSONString.claimJSON, function (i, v) {
        alert("v::" + v.tranID);
}); 

claimJSONString alerts as :

{
"claimJSON": [
    {
        "tranID": "12581",
        "a": "0",
        "b": "0",
        "c": "0",
        "d": "0"
    }
]
}

Also tried

J.each(jsonString, function (i, v) {
        alert("v::" + v.tranID);
}); 

where jsonString is { "tranID": "12581", "a": "0", "b": "0", "c": "0", "d": "0" } now the error is Object Expected.

What am I doing wrong?

P.S. I am close to tearing my hair out. Please Help! P.S.S Jquery Newbie

V G
  • 117
  • 4
  • 14
  • 1
    a json string is not a javascript object. you need to parse the json first. see http://stackoverflow.com/questions/4935632/parse-json-in-javascript – The Scrum Meister Nov 26 '14 at 07:04

1 Answers1

2

You need to parse JSON Object from json string, use jQuery.parseJSON() or JSON.parse() methods, see below sample code

var  claimJSONString = jQuery.parseJSON('{"claimJSON": [' + jsonString + ']}');

And in each loop use claimJSONString.claimJSON[0] because your object in [0] index

J.each(claimJSONString.claimJSON[0], function (i, v) {
       alert("v::" + v.tranID);
});
Girish
  • 11,907
  • 3
  • 34
  • 51