为什么JSON.parse失败并带有空字符串? [英] Why does JSON.parse fail with the empty string?

查看:702
本文介绍了为什么JSON.parse失败并带有空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么:

JSON.parse('');

产生错误?

Uncaught SyntaxError: Unexpected end of input

这不是更合乎逻辑如果刚刚返回 null

Wouldn't it be more logical if it just returned null?

推荐答案

因为空字符串不是有效的JSON, JSON.parse('')返回 null 是不正确的,因为 null是有效的JSON。例如

As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g.

JSON.parse("null");

返回 null 。将无效JSON也解析为null将是一个错误。

returns null. It would be a mistake for invalid JSON to also be parsed to null.

虽然空字符串无效,但JSON两个引号是有效的JSON。这是一个重要的区别。

While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.

这就是说包含两个引号的字符串与空字符串不同。

Which is to say a string that contains two quotes is not the same thing as an empty string.

JSON.parse('""');

将正确解析,(返回一个空字符串)。但是

will parse correctly, (returning an empty string). But

JSON.parse('');

不会。

有效的最小JSON字符串是

Valid minimal JSON strings are

空对象'{}'

空数组'[]'

空字符串' '

一个例如'123.4'

布尔值true 'true'

布尔值false 'false'

空值'null'

这篇关于为什么JSON.parse失败并带有空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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