除了字符串和数字之外,有效的JSON还可包含特殊值,例如null
和false
我需要解析由一些还包含undefined
的API生成的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的方法?如果不是,修复此错误JSON的最佳方法是什么?
我曾考虑过简单地gsubbing undefined
,但这是有风险的,因为该单词很容易存在于JSON字符串值中。
Nope。您cannot解析具有未定义值的JSON; undefined确实是一个特殊值。实际上,undefined
作为“值”一定不能出现在有效的JSON中,并且旨在表示“此键[在您的情况下,"Sepal.Width"
]不存在”。相反,该API可能有故障,它正在生成具有undefined
值的JSON。
[官方消息,The JSON Data交换语法,指出
JSON值可以是对象,数组,数字,字符串,true,false或null。
最佳解决方法是检查JSON生成器或API,以及为什么它在JSON中生成undefined
。您还可以手动或算法修复有缺陷的JSON,并检查JSON中是否存在任何不一致之处。
为了记录,我用str_replace_all()
用:undefined
代替了:"undefined"
。
这有点冒险,因为如果字符串:undefined
恰好出现在JSON的实际字符串值中,则将引起问题,但就我而言,这是(不完善的)解决方案
str_replace_all(invalid_json, ':undefined', ':"undefined"')