0

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.

4

2 に答える 2

4

JSONドキュメントを返すHTTP応答があるようです。

[JSON]タブでは、これはJSONとして表示されます。

コードの場合は、応答のテキストを取得して操作しているだけです。

JavaScriptオブジェクトを作成するには、JSONを解析する必要があります。

文字列を渡し、 json2.jsJSON.parseを使用して古いブラウザのポリフィルを作成します。

于 2012-07-30T09:36:49.687 に答える
2

JSON を解析して JavaScript 配列を作成する必要があります。

result = JSON.parse(result); // Now it's an array
console.log(result.length) // prints now what you want
于 2012-07-30T09:39:40.953 に答える