You will see following error if json String contains values other string or numbers. For example it can happen if you are parsing the data from the Ajax request.
In [1]:
letjsonString='{"name":"John", "age": 5, "name":"Alex", "age":NaN}';In [2]:
JSON.parse(jsonString);
undefined:1
{"name":"John", "age": 5, "name":"Alex", "age":NaN}
^
SyntaxError: Unexpected token N in JSON at position 47
at JSON.parse (<anonymous>)
at evalmachine.<anonymous>:1:6
at Script.runInThisContext (node:vm:129:12)
at Object.runInThisContext (node:vm:305:38)
at run ([eval]:1020:15)
at onRunRequest ([eval]:864:18)
at onMessage ([eval]:828:13)
at process.emit (node:events:526:28)
at emit (node:internal/child_process:938:14)
at processTicksAndRejections (node:internal/process/task_queues:84:21)To fix this remove the value which is not a string or number. We can replace the value with null, null is valid keyword.
In [3]:
letcleanedJsonString=jsonString.replace(/NaN/g,'null');Let us try now to parse the cleaned json string.
In [4]:
JSON.parse(cleanedJsonString);Out[4]:
{ name: 'Alex', age: null }