简体   繁体   English

JSON.parse输出一个字符串

[英]JSON.parse is outputting a string

What's going on here? 这里发生了什么?

var data = '"[2743,1,1,1,1,1]"';
var flags = JSON.parse(data);
console.log(typeof flags);      // this outputs "string"

I was expecting flags to be an object or array, but it's a string. 我期望flags是一个对象或数组,但这是一个字符串。 The MDN Web Docs say, "The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string." MDN Web文档说:“ JSON.parse()方法解析JSON字符串,构造JavaScript值或该字符串描述的对象。” Also: 也:

Return value 返回值
The Object corresponding to the given JSON text. 与给定JSON文本相对应的Object。

Exceptions 例外情况
Throws a SyntaxError exception if the string to parse is not valid JSON. 如果要解析的字符串无效的JSON,则引发SyntaxError异常。

var data = '"[2743,1,1,1,1,1]"';

This is a string containing a string. 这是一个包含字符串的字符串。 When you parse it with 当您解析时

var result = JSON.parse(data);

What you get is the string 你得到的是字符串

"[2743,1,1,1,1,1]"

If you parse that a second time you will get your array of flags. 如果您第二次解析,则将获得标志数组。

Try this 尝试这个

var flags = JSON.parse(JSON.parse(data));

Looks like it's an object and everything's OK, check the snippet: 看起来像是一个对象,一切正常,请检查代码段:

 var data = '[2743,1,1,1,1,1]'; var flags = JSON.parse(data); console.log(typeof flags); console.log(flags); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM