Parse JSON with special 'undefined' value?

本秂侑毒 提交于 2019-12-23 06:37:46

问题


In addition to strings and numbers, valid JSON can contain special values null and false

I need to parse JSON that also contains undefined, which is a valid javascript value, but not a valid JSON value

Example

library(jsonlite)

# A string works
"[{\"Sepal.Width\":\"3.5\"}]" %>% fromJSON
#  Sepal.Width
#         3.5

# A number works
"[{\"Sepal.Width\":3.5}]"  %>% fromJSON
#  Sepal.Width
#         3.5

# null works
"[{\"Sepal.Width\": null}]" %>% fromJSON
#  Sepal.Width
#          NA

# false works
 "[{\"Sepal.Width\": false}]" %>% fromJSON
#  Sepal.Width
#       FALSE

# undefined does not work
 "[{\"Sepal.Width\": undefined}]" %>% fromJSON
Error: lexical error: invalid char in json text.
                      [{"Sepal.Width": undefined}]
                     (right here) ------^

Question

Is there any (reliable) way to parse JSON containing undefined?

Note

I've thought about simply gsubbing undefined, but that is risky, since that word could easily exist in the JSON string values.


回答1:


You cannot parse a JSON with an undefined value; undefined is special. In fact, undefined as a "value" must not occur in valid JSON.

The official source, The JSON Data Interchange Syntax, states that

A JSON value can be an object, array, number, string, true, false, or null.

The best remedy is to examine the JSON generator and why it generates undefined in a JSON.



来源:https://stackoverflow.com/questions/59304404/parse-json-with-special-undefined-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!