Home > Enterprise >  How to adapt JSON.Parser for NaN in Javascript?
How to adapt JSON.Parser for NaN in Javascript?

Time:05-24

I'm trying to adapt JSON.Parse() for NaN.

console.log(JSON.parse('{"n": 1}'));
console.log(JSON.parse('{"n": NaN}'));

1st one is {n:1}.

2nd one has an error which says Unexpected token N in JSON. And I want to change NaN to 0 like {n: 0}.

I found a resource which create JSON Parser from scratch.https://lihautan.com/json-parser-with-javascript/#implementing-the-parser

It's good he separates keys and values so that I can check only values if there is NaN and fix it. But the problem is I have no idea where I can put the NaNParser() and the process. Because the parameter looks coming 1 by 1 character.

If you could give me some advice, it really helps me. https://codesandbox.io/s/json-parser-with-error-handling-hjwxk?from-embed

CodePudding user response:

"Hacky" solution:

var json = '{"n": NaN}';

var object = JSON.parse(json.replace("NaN", "\"NaN\""));
for(var key in object)
{
    if(object[key] == "NaN")
    {
        object[key] = NaN;
    }
}

console.log(object);

This replaces all NaN values in the JSON with the string "NaN", then runs that through JSON.parse, and then re-replaces all "NaN" string in the object with actual NaN.

CodePudding user response:

Context

Note that JSON.stringify({"n": NaN})

outputs: '{"n":null}'

This means that:

  • NaN is not a valid serialised value.
  • by default it is converted to null not 0 (because it's not a number)

Solution

Perhaps the fastest approach is to simply replace all NaN values before parsing it.

const input = '{"o": 1, "n": NaN, "m": "test"}'

const output = input.replace(/(:\s*)NaN(\s*[,}])/, '$1null$2')

console.log(output) // prints: '{"o": 1, "n": null, "m": "test"}'
  • Related