How to represent a sparse array in JSON?

I have a sparse array that I want to represent in JSON. For instance:

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

How can i do this? Can I do it?

+3
source share
2 answers

You can imagine it as a simple object:

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

Since this will be a simple object, you cannot repeat it in the same way as an array, but you can use the for...in operator

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

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

 obj['-10']; // 100 

Note that I use the hasOwnProperty method inside for...in , this prevents iterative properties defined at higher levels of the prototype chain, which can cause problems and unexpected behavior ... more details here .

+7
source

Yes, you can. The names of the members of the JSON object are strings. Strings can contain any UTF-8 encoded value:

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

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


All Articles