除了字符串和数字外,有效的JSON还可包含特殊值null
和false
我需要解析还包含由API生成的undefined
的JSON。 undefined
是valid javascript value,但它不是有效的JSON值。
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) ------^
是否有(可靠)解析包含undefined
的JSON的方法?
我曾考虑过简单地gsubbing undefined
,但这是有风险的,因为该单词很容易存在于JSON字符串值中。
您无法解析具有未定义值的JSON; undefined是特殊的。实际上,undefined
作为“值”一定不能出现在有效的JSON中。相反,该API可能是错误的,正在使用undefined
值生成JSON。
[官方消息,The JSON Data交换语法,指出
JSON值可以是对象,数组,数字,字符串,true,false或null。
最佳解决方法是检查JSON生成器或API,以及为什么它在JSON中生成未定义的原因。