Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON string is treated as a literal string in loop

I suspect this is an easy problem, but I am a bit new to js and can't find the solution.

Basically, when I pass a JSON string to a function and then attempt to iterate through the passed variable, it treats it like a literal string rather than an array.

With this function:

function build_codes_long(codes) {
   var codes_long_text = "";
   for(var i =0;i < codes.length-1;i++) {
      var code = codes[i];
      codes_long_text += "<p>" + code['id'] + " = " + code['del'] + "</p>";
   }
return codes_long_text; 
}

When I pass a JSON string to it like:

[{"id":"1","del":"0","clip":"1"},{"id":"2","del":"0","clip":"1"}]

It evaluates each character in the string, rather than each item in the array. So it loops 65 times instead of 2, returning something like:

undefined = undefined

I understand the problem with the returned values; it's the treating the array like a literal string I don't understand. Thanks!

like image 815
David Farrell Avatar asked May 25 '12 17:05

David Farrell


1 Answers

It's because you're not looping through an object; you're looping through a string and getting each letter as a result.

You need to convert the JSON string to an object first:

var myObject = JSON.parse(myJsonString);
var codesLongText = build_codes_long(myObject);
like image 102
Jonathan M Avatar answered Oct 21 '22 11:10

Jonathan M