[javascript] how to count length of the JSON array element

I'm trying to count the length of the JSON array element. I know to count the length of array using json.array.length. That is need to find that how many items in every index.

If my array is:

{
  "shareInfo": [{
      "id": "1",
      "a": "sss",
      "b": "sss",
      "question": "whi?"
    },
    {
      "id": "2",
      "a": "sss",
      "b": "sss",
      "question": "whi?"
    },
    {
      "id": "3",
      "a": "sss",
      "b": "sss",
      "question": "whi?"
    },
    {
      "id": "4",
      "a": "sss",
      "b": "sss",
      "question": "whi?"
    }
  ]
}

Then I need to find the length of {"id":"1","a":"sss","b":"sss","question":"whi?"}. In this there have four items. I tried this with data.shareInfo[i].length. But it produces error.

Please anyone tell me how to find the length.... Thanks....

This question is related to javascript jquery

The answer is


Before going to answer read this Documentation once. Then you clearly understand the answer.

Try this It may work for you.

Object.keys(data.shareInfo[i]).length

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

First, there is no such thing as a JSON object. JSON is a string format that can be used as a representation of a Javascript object literal.

Since JSON is a string, Javascript will treat it like a string, and not like an object (or array or whatever you are trying to use it as.)

Here is a good JSON reference to clarify this difference:

http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/

So if you need accomplish the task mentioned in your question, you must convert the JSON string to an object or deal with it as a string, and not as a JSON array. There are several libraries to accomplish this. Look at http://www.json.org/js.html for a reference.


I think you should try

data = {"shareInfo":[{"id":"1","a":"sss","b":"sss","question":"whi?"},
{"id":"2","a":"sss","b":"sss","question":"whi?"},
{"id":"3","a":"sss","b":"sss","question":"whi?"},
{"id":"4","a":"sss","b":"sss","question":"whi?"}]};

ShareInfoLength = data.shareInfo.length;
alert(ShareInfoLength);
for(var i=0; i<ShareInfoLength; i++)
{
alert(Object.keys(data.shareInfo[i]).length);
}