DEV Community

How to fix JSON.stringify returning an empty object

Kameron Kales on May 06, 2019

I write a lot of Javascript and ran into a pretty awful bug today that took me 3 hours to figure out. In the hopes of this saving someone else an e...
Collapse
 
holgeradam profile image
Holger Adam • Edited

Hey there,

thanks for writing this.

I tried this and it works for me with node 11. Maybe I'm missing something?
The console output for your initial example list looks like an object judging by the curly braces.

This is what the node REPL does for me:

|> JSON.stringify({1:"abc"})
'{"1":"abc"}'

|> let x = []
undefined
|> x[1] = "abc"
'abc'
|> JSON.stringify(x)
'[null,"abc"]'

As you can see both numbers as property names and arrays with unset indexes work fine with JSON.stringify.

Collapse
 
kingkong88 profile image
Kingg Kongg

Numerical property names are in the specs. I think author's screenshot of first log { 0: ..., 1:... } is not correct.

Collapse
 
canismail profile image
canismail

Thanks for writing. It s really helpfull for me