pi.
pi.

Reputation: 1471

How to get the right count NOT character length of JSON data

My code returns a JSON array, I think. The returned JSON array is stored in a javascript variable: result. If I

console.log(result); 

in FF, I get the output

[{"id":"G24","value":"Zas, S"},{"id":"G75","value":"Wara, TS"},{"id":"G48","value":"Jala, S"}]

Validated on jsonLint to be correct json.

In my code, if I count the number of elements in the array like so:

var key, count = 0;
for(key in result) 
{
  count++;
}
console.log("result count is:" + count); 

The output is 94 which is the length/count of characters in the array - [the sample output shown above is modified]

However, in the JSON tab in FF, it shows the result as being an array of objects:

0   Object { id="G24", value="Zas, S"}
1   Object { id="G75", value="Wara, TS"}
2   Object { id="G48", value="Jala, S"}

I have used alternative code pieces from 'stackoverflow' sources

for ( property in result )
{
   if(result.hasOwnProperty(property))
   {
     count++;
   }
}

And this has had the same outcome. How can I have iterate rightly over this array or array of objects or string or whatever else it is? And get the count please?. Thanks.

Upvotes: 1

Views: 2850

Answers (2)

Bruno Schäpper
Bruno Schäpper

Reputation: 1302

You have to parse the JSON to create a JavaScript Array.

result = JSON.parse(result); // Now it's an array
console.log(result.length) // prints now what you want

Upvotes: 3

Quentin
Quentin

Reputation: 943560

It sounds like you have an HTTP response returning a JSON document.

In the JSON tab, this is shown as JSON.

If your code, you are just taking the text of the response and operating on that.

You need to parse the JSON to create JavaScript objects.

Pass the string through JSON.parse and use json2.js to polyfill for older browsers.

Upvotes: 4

Related Questions