How to represent a sparse array in JSON?

好久不见. 提交于 2019-12-01 07:19:46

问题


I've got a sparse array that I want to represent in JSON. For example:

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

How can I do this? Can I do this?


回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/1733658/how-to-represent-a-sparse-array-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!