JSON implementations that process sparse arrays

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

My minimum requirement would be that the implementation fill any undefined spaces. Otherwise, I write security code that fills in the blanks myself, before encoding JSON.

+4
source share
2 answers

Impossible. Forget about the implementation, it is simply not allowed in the specification.

http://json.org/

Arrays are defined only by value. Objects refer to the index / key value.

+5
source

Could you use an object where the property name was an index and the property value was a value, and 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; } 

Would you send something like

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

and return an array that was filled with just three values:

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

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

+2
source

Source: https://habr.com/ru/post/1307177/


All Articles