为什么JSON.parse([' 1234'])返回1234?

时间:2017-05-01 10:57:22

标签: javascript arrays json

我在理解JSON.parse的行为时遇到了问题。 JSON.parse应仅适用于字符串。但它似乎适用于只包含一个字符串(甚至是单引号)的数组,如果字符串只包含数字。

JSON.parse(['1234']) // => 1234
JSON.parse(['1234as']) // => throws error
JSON.parse(['123', '123']) // => throws error

3 个答案:

答案 0 :(得分:180)

正如您所指出的,JSON.parse()需要字符串而不是数组。但是,当给定数组或任何其他非字符串值时,该方法将自动将其强制转换为字符串并继续而不是立即抛出。来自spec

  
      
  1. 让JText为ToString(文本)。
  2.   
  3. ...
  4.   

数组的字符串表示形式由其值组成,以逗号分隔。所以

  • String(['1234'])返回'1234'
  • String(['1234as'])返回'1234as'
  • String(['123', '123'])返回'123,123'

请注意,不会再次引用字符串值。这意味着['1234'][1234]都转换为相同的字符串'1234'

所以你真正做的是:

JSON.parse('1234')
JSON.parse('1234as')
JSON.parse('123,123')

1234as123,123无效JSON,因此JSON.parse()会引发两种情况。 (前者不是合法的JavaScript语法,后者包含不属于的逗号运算符。)

另一方面,

1234是一个数字文字,因此是有效的JSON,代表自己。这就是JSON.parse('1234')(和扩展名JSON.parse(['1234']))返回数值1234的原因。

答案 1 :(得分:21)

如果JSON.parse没有获取字符串,它将首先将输入转换为字符串。

["1234"].toString() // "1234"
["1234as"].toString() // "1324as"
["123","123"].toString() // "123,123"

从所有这些输出中,它只知道如何解析“1234”。

答案 2 :(得分:4)

这里有两点需要注意:

1)JSON.parse将参数转换为字符串(请参阅规范中算法的第一步)。您的输入结果如下:

['1234']       // String 1234
['1234as']     // String 1234as
['123', '123'] // String 123,123

2)json.org的规格说明:

  

[...]值可以是双引号中的字符串,也可以是数字或true   或false或null,或对象或数组。这些结构可以   嵌套。

所以我们有:

JSON.parse(['1234'])
// Becomes JSON.parse("1234")
// 1234 could be parsed as a number
// Result is Number 1234 

JSON.parse(['1234as'])
// Becomes JSON.parse("1234as")
// 1234as cannot be parsed as a number/true/false/null
// 1234as cannot be parsed as a string/object/array either
// Throws error (complains about the "a")

JSON.parse(['123', '123'])
// Becomes JSON.parse("123,123")
// 123 could be parsed as a number but then the comma is unexpected
// Throws error (complains about the ",")
相关问题