解析或修复具有特殊 'undefined' 值的 JSON?
Parsing or fixing JSONs with special 'undefined' values?
除了字符串和数字,有效的 JSON 还可以包含特殊值,例如 null
和 false
我需要解析由某些 API 生成的 JSON,其中还包含 undefined
。然而,undefined
是一个 valid JavaScript value,但它不是一个有效的 JSON 值,每当我解析它时 returns 一个 词法错误 .
示例:
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 字符串值中。
不行。 您不能 解析具有未定义值的 JSON; undefined 确实是一个特殊的值。事实上,作为 "value" 的 undefined
一定不能出现在有效的 JSON 中,并且意在表示 "this key [in your case, "Sepal.Width"
] doesn't exist." 相反,API 可能是错误的,它在哪里正在生成具有 undefined
值的 JSONs。
官方出处,The JSON Data
交换语法,声明
A JSON value can be an object, array, number, string, true, false, or null.
最好的补救方法是检查 JSON 生成器或 API 以及它在 JSON 中生成 undefined
的原因。您也可以手动或通过算法修复有缺陷的JSON,并检查您的JSON.
是否有任何不一致之处
郑重声明,我用 str_replace_all()
将 :undefined
替换为 :"undefined"
。
这有点冒险,因为如果字符串 :undefined
恰好出现在 JSON 中的实际字符串值中,它会导致问题,但在我的情况下,它是(不完美的)解决方案
str_replace_all(invalid_json, ':undefined', ':"undefined"')
除了字符串和数字,有效的 JSON 还可以包含特殊值,例如 null
和 false
我需要解析由某些 API 生成的 JSON,其中还包含 undefined
。然而,undefined
是一个 valid JavaScript value,但它不是一个有效的 JSON 值,每当我解析它时 returns 一个 词法错误 .
示例:
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 字符串值中。
不行。 您不能 解析具有未定义值的 JSON; undefined 确实是一个特殊的值。事实上,作为 "value" 的 undefined
一定不能出现在有效的 JSON 中,并且意在表示 "this key [in your case, "Sepal.Width"
] doesn't exist." 相反,API 可能是错误的,它在哪里正在生成具有 undefined
值的 JSONs。
官方出处,The JSON Data 交换语法,声明
A JSON value can be an object, array, number, string, true, false, or null.
最好的补救方法是检查 JSON 生成器或 API 以及它在 JSON 中生成 undefined
的原因。您也可以手动或通过算法修复有缺陷的JSON,并检查您的JSON.
郑重声明,我用 str_replace_all()
将 :undefined
替换为 :"undefined"
。
这有点冒险,因为如果字符串 :undefined
恰好出现在 JSON 中的实际字符串值中,它会导致问题,但在我的情况下,它是(不完美的)解决方案
str_replace_all(invalid_json, ':undefined', ':"undefined"')