How to parse JSON string containing “NaN” in Node.js

后端 未结 4 1413
盖世英雄少女心
盖世英雄少女心 2020-12-17 08:24

Have a node.js app that is receiving JSON data strings that contain the literal NaN, like

 \"[1, 2, 3, NaN, 5, 6]\"

This crashes JSON

4条回答
  •  醉话见心
    2020-12-17 09:00

    You can use JSON5 library. A quote from the project page:

    The JSON5 Data Interchange Format (JSON5) is a superset of JSON that aims to alleviate some of the limitations of JSON by expanding its syntax to include some productions from ECMAScript 5.1.

    This JavaScript library is the official reference implementation for JSON5 parsing and serialization libraries.

    As you would expect, among other things it does support parsing NaNs (compatible with how Python and the like serialize them):

    JSON5.parse("[1, 2, 3, NaN, 5, 6]")
    > (6) [1, 2, 3, NaN, 5, 6]
    

提交回复
热议问题