gpt4 book ai didi

javascript - 为什么 obj.getAttribute 中的 json 字符串不想解析?

转载 作者:行者123 更新时间:2023-12-02 19:40:23 26 4
gpt4 key购买 nike

var jsn=getAttr(ref,"json-data").toString();
console.log(jsn); //{test: true,stringtest:"hallo"}. it's OK.
JSON.parse(jsn); //Uncaught SyntaxError: Unexpected token s, line: line with JSON.parse;

我认为JSON.parse这个数据做了一些不正确的事情..我试图删除 stringtest:"hallo" - 没有结果... PS:我也认为我做错了什么然后我问了这个问题

第一次尝试JSON.parse("{"+jsn+"}"); .

最佳答案

您的 JSON 格式不正确,因为您的对象键必须用引号引起来。以下内容将起作用:

var jsn = '{"test": true, "stringtest": "hallo"}';
JSON.parse(jsn);

编辑:指定 JSON 格式的 RFC4627 指出:

2.2. Objects

An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string
. A single colon comes after each name, separating the name
from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.

  object = begin-object [ member *( value-separator member ) ]
end-object

member = string name-separator value

如您所见,JSON 对象由名称/值对组成,其中名称是字符串。 RFC 再次指出:

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with
quotation marks
. All Unicode characters may be placed within the
quotation marks except for the characters that must be escaped:
quotation mark, reverse solidus, and the control characters (U+0000
through U+001F).

string = quotation-mark *char quotation-mark

quotation-mark = %x22 ; "

因此,根据 RFC,键必须用双引号括起来,而不是单引号。不过,我想有些解析器可能更宽容并接受它们两者,但我会坚持标准。

关于javascript - 为什么 obj.getAttribute 中的 json 字符串不想解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10456911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com