DEV Community

Some Things About JSON That You May Have Missed

John Au-Yeung on January 04, 2020

Subscribe to my email list now at http://jauyeung.net/subscribe/ Follow me on Twitter at https://twitter.com/AuMayeung Many more articles at http...
Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

Another hidden ability of JavaScript JSON is Date.prototype.toJSON, which will customize JSON.stringify behavior of the object.

Collapse
 
aumayeung profile image
John Au-Yeung

Thanks for finding that.

That's a method that most people don't think of using.

Collapse
 
stephenmirving profile image
Stephen Irving • Edited

Just so you know, including multiple return paths for functions is an anti-pattern/code-smell. It is a best practice for a function to only have a single return path if that is possible. So, for example, in your third to last snippet, you could have written the replacer function like this instead and have what it returns be the same (I also fixed your NaN check to use Number.isNaN() because using equality to check against NaN will not work as expected):

const replacer = (key, value) => (
  typeof value === 'undefined'
    ? 'undefined'
    : (
      value instanceof Function || Number.isNaN(value) || value === Infinity
        ? value.toString()
        : value
    )
);
Collapse
 
petergabriel2 profile image
PeterGabriel2 • Edited

Absolutely wrong! In every case is switch more readable than joined or/and superlongline. More easy to update. And you will not make error in it so easily like in bunch of writeonly code you just wrote.

Collapse
 
aumayeung profile image
John Au-Yeung

I think ternary operator shouldn't be nested. It's harder to read than if or switch like you said.

Collapse
 
nicojs profile image
Nico Jansen

value === NaN is always false. For example NaN === NaN. Use isNaN().

Collapse
 
aumayeung profile image
John Au-Yeung

Thanks. That's a good catch.

Collapse
 
stephenmirving profile image
Stephen Irving

You should actually be using Number.isNan() over the global isNaN function which will give somewhat unexpected results in comparison to the newer method on the Number object. You should also use !Number.isFinite() instead of checking equality with Infinity.

Thread Thread
 
aumayeung profile image
John Au-Yeung

Thanks. That's also a good tip.

I think equality is still good as long as we use triple equals.

Thread Thread
 
stephenmirving profile image
Stephen Irving

Yes, you can still write it that way.

Collapse
 
sams4s profile image
sam-s4s

Also if the object or class that you're converting has a toJSON function, it will use that to determine the output - can be very handy :)

developer.mozilla.org/en-US/docs/W...

Collapse
 
aumayeung profile image
John Au-Yeung

Yea. Then we don't have to passing a mapping function every time we want to stringify. I think URL and URLSearchParams objects have this method.