开发者

How to represent a sparse array in JSON?

开发者 https://www.devze.com 2022-12-11 05:09 出处:网络
I\'ve got a sparse array that I want to represent in JSON. F开发者_开发技巧or example: -10 => 100

I've got a sparse array that I want to represent in JSON. F开发者_开发技巧or example:

  -10 => 100
   -1 => 102
    3 => 44
   12 => -87
12345 => 0

How can I do this? Can I do this?


You can represent it as a simple object:

{
  "-10" : 100,
  "-1" : 102,
  "3" : 44,
  "12" : -87,
  "12345" : 0
}

Since it will be a simple object, you cannot iterate it the same way as an array, but you can use the for...in statement:

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var value = obj[key];
  }
}

And if you want to access an specific element by key, you can use also here the square bracket property accessor:

obj['-10']; // 100

Note that I use the hasOwnProperty method inside the for...in loop, this is to prevent iterating properties defined on higher levels of the prototype chain, which can cause problems and unexpected behavior... more info here.


Yes, you can. JSON object members name are strings. Strings can hold any UTF-8 encoded value:

{
  "-10"   : 100,
  "-1"    : 102,
  "3"     : 44,
  "12"    : -87,
  "12345" : 0
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号