简体   繁体   中英

Find the length of an JSON object

I have a JSON like the following. How can I find the length of air in console,

console.log (block.number.path[i].air.length);

{ "block": [
    { "number": "36",
      "path": [
          { "air": "[{\"name\":\"0\"},{\"name\":\"1\"},{\"name\":\"2\"}]" },
          { "water": "[{\"name\":\"3\"},{\"name\":\"4\"},{\"name\":\"5\"}]" },
          { "sand": "[{\"name\":\"6\"},{\"username\":\"7\"},{\"name\":\"8\"}]" }
      ]
    }
  ]
}

air itself contains a JSON encoded array, which you have to decode first:

// your obj in here
var obj = { "..." : "..." };

// grab the respective length of the "air" attribute
var air = JSON.parse( obj.block[0].path[0].air );
console.log( air.length );

http://jsfiddle.net/pLAny/

You can solve this like so:

var length = JSON.parse(block.number.path[i].air).length;
console.log(length);

It kind of looks like some of that JSON got malformed. "air", "water", and "sand" are all JSON arrays...but parsed out into strings. If you're the one generating the JSON, look into that, because it doesn't seem right. As the other answers point out, it's still solvable in Javascript using JSON.parse() , as long as you can be sure your target browsers have that interface (most modern ones).

For any JSON array (anything declared using [] brackets) you can check its .length property.

假设json是一个包含JSON的变量,则可以执行以下操作:

json["block"][0]["path"][0]["air"].length

Block is an array, so you have to access to the element first:

a.block[0].path[0].air.length

where a is the variable where you are holding the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM