How to keep NaN value after stringify

Viewed 66

I have a object contains NaN, I would like to keep its type, after stringify.

const api = { x: 5, y: NaN }

console.log(JSON.stringify( api ));


// output  '{"x":5,"y":null}' 

//but I expect  '{"x":5,"y":NaN}'  

The reason I want to make it appear as NaN is that this json is preparing for python to process. And in the python code, they can only handle NaN, but not null. This I can not contronl

1 Answers

Since JSON does not support NaN i suggets writing your own custom replacer function.

const api = { x: 5, y: NaN }

function replacer(key, value) {
  return Number.isNaN(value) ? "NaN" : value
}
console.log(JSON.stringify(api, replacer));

And appropriate parser

const jsonData = '{"x":5,"y":"NaN"}';

function parser(key, val) {
    return val === "NaN" ? NaN : val;
}

console.log(JSON.parse(jsonData, parser));

Javascript object and JSON are not the same. JSON is just an open standard file format and data interchange format. It's format is similar to that of javascript objects but not the same.

JSON cannot contain long ints, NaNs, functions, symbols, circular references etc.

Related