4

I need to know if any JSON implementations can handle sparse arrays to my satisfaction. I've seen the question: How to represent a sparse array in JSON? but using an object rather than an array is not an option for me; I need an array.

My minimum requirement would be that the implementation fill in any gaps with "undefined". Otherwise I am writing defensive code that fills in the gaps myself, before JSON encoding.

Community
  • 1
  • 1
Dexygen
  • 12,287
  • 13
  • 80
  • 147

2 Answers2

5

Not possible. Forget implementations, it's just plain not allowed in the spec.

http://json.org/

Arrays are defined by value only. Objects are for when the index/key has meaning.

Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • 1
    ... and "undefined" is not a JSON value – Pointy Apr 16 '10 at 19:22
  • point(s) taken; would therefore fill in gaps with null instead – Dexygen Apr 16 '10 at 20:03
  • Well, the problem is that JSON is JSON, and there's no way to directly represent a "sparse array" such that any arbitrary JSON parser will understand it. However, if you're happy with transforming the array on the way "in" and "out" of JSON, then @Robusto's answer is what you'd want to look at. – Pointy Apr 16 '10 at 20:08
2

Could you use an object where the property name was an index and the property value was the value, then run it through an intermediary function to create your sparse array?

function getSparseArray(obj) {
  var ary = [];
  for (prop in obj) {
    var i = parseInt(prop,10);
    if (!isNaN(i)) {
      ary[i] = obj[prop];
    }
  }
  return ary;
}

You would send it something like

{ "5":"Five", "11":"Eleven", "99":"Ninety-Nine"}

and get back an array that was populated with just three values:

ary[5] = "Five"
ary[11] = "Eleven"
ary[99] = "Ninety-Nine"
ary[0] = 'undefined'
ary[98] = 'undefined'
etc.

ary here would have a length of 100, but it would be a "sparse" array in your sense.

Robusto
  • 31,447
  • 8
  • 56
  • 77
  • I don't think this is what was asked for, but I agree that it's the best way to go. Of course, one might wonder whether a plain JSON array with lots of "null" values would gzip down to something smaller anyway! – Pointy Apr 16 '10 at 19:26
  • @Pointy: Yeah, for most use cases you're probably right. As soon as you decided that's the limit, though, someone is almost certain to send you an index of 10000000. :) – Robusto Apr 16 '10 at 19:50
  • 1
    @JoeLove: Ask the OP. He was asking for an edge-case implementation anyway. (And that was nine years ago.) – Robusto Mar 08 '19 at 20:40
  • Thanks, I misread the OPs question. I didn't realize that gaps were to be filled with that string. Thanks for responding. – Joe Love Mar 08 '19 at 22:00