JSON.parse()
会把一个字符串解析成 JSON 对象。若是字符串书写正确,那么其将会被解析成一个有效的 JSON,可是这个字符串被检测出错误语法的时候将会抛出错误。数组
JSON.parse()
不容许在末尾添加多余的逗号下面两行代码都会抛出错误:函数
1 JSON.parse('[1, 2, 3, 4, ]'); 2 JSON.parse('{"foo" : 1, }'); 3 // SyntaxError JSON.parse: unexpected character 4 // at line 1 column 14 of the JSON data
省略末尾多余的逗号解析 JSON 就是正确:spa
1 JSON.parse('[1, 2, 3, 4 ]'); 2 JSON.parse('{"foo" : 1 }');
属性名上不能使用单引号,例如: 'foo'。code
1 JSON.parse("{'foo' : 1 }"); 2 // SyntaxError: JSON.parse: expected property name or '}' 3 // at line 1 column 2 of the JSON data
取而代之,写成 "foo":对象
1 JSON.parse('{"foo" : 1 }');
数字不能用 0 开头,好比01,而且你的小数点后面必须跟着至少一个数字。blog
1 JSON.parse('{"foo" : 01 }'); 2 // SyntaxError: JSON.parse: expected ',' or '}' after property value 3 // in object at line 1 column 2 of the JSON data 4 5 JSON.parse('{"foo" : 1. }'); 6 // SyntaxError: JSON.parse: unterminated fractional number 7 // at line 1 column 2 of the JSON data
正确的写法应该是只写一个1,不书写前面的0。在小数点的后面至少要跟上一个数字:ip
1 JSON.parse('{"foo" : 1 }'); 2 JSON.parse('{"foo" : 1.0 }');