问题
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