解析或修复具有特殊“未定义"值的JSON? [英] Parsing or fixing JSONs with special 'undefined' values?

查看:88
本文介绍了解析或修复具有特殊“未定义"值的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了字符串和数字外,有效的JSON还可以包含特殊值,例如nullfalse

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

我需要解析由也包含undefined的某些API生成的JSON.但是,undefined有效的JavaScript值,但它不是有效的JSON值,因此无论何时我解析它返回词法错误.

I need to parse a JSON generated by some API that also contains undefined. However, undefined is a valid JavaScript value, but it is not a valid JSON value, and whenever I parse it it returns a lexical error.

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的最佳方法是什么?

Question:

Is there any (reliable) way to parse JSON containing undefined values? If not, what is the best approach to repair this faulty JSON?

我曾经考虑过简单地gsubbing undefined,但这是有风险的,因为该单词很容易存在于JSON字符串值中.

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

推荐答案

否.无法解析具有未定义值的JSON; undefined确实是一个特殊值.实际上,undefined作为值"一定不能出现在有效的JSON中,并且旨在表示此键[在您的情况下,"Sepal.Width"]不存在".相反,该API可能是错误的,它正在生成具有undefined值的JSON.

Nope. You cannot parse a JSON with an undefined value; undefined is indeed a special value. In fact, undefined as a "value" must not occur in valid JSON, and is intended to mean "this key [in your case, "Sepal.Width"] doesn't exist." Instead, the API is likely faulty, where it is generating JSONs with undefined values.

官方资料, JSON数据 交换语法,指出

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

JSON值可以是对象,数组,数字,字符串,true,false或null.

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

最好的解决方法是检查JSON生成器或API,以及为什么它在JSON中生成undefined.您还可以手动或通过算法修复有缺陷的JSON,并检查JSON中是否存在任何不一致之处.

The best remedy is to examine the JSON generator or API and why it generates undefined in a JSON. You can also manually or algorithmically repair the defective JSON, and check if there are any inconsistencies in your JSON.

这篇关于解析或修复具有特殊“未定义"值的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆