How to represent a sparse array in JSON?
Asked Answered
S

2

6

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?

Sigma answered 14/11, 2009 at 8:11 Comment(0)
T
9

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.

Tibetan answered 14/11, 2009 at 8:22 Comment(1)
Yeah, I don't think you could really iterate it as an Array in the normal way anyway, since there are negative indices. Object it is.Lathy
H
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
}
Housekeeping answered 14/11, 2009 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.