SyntaxError:来自angularjs的chrome控制台中的意外标记N.

Jos*_*vid 13 javascript angularjs

嗨,我通过chrome控制台使用angularjs得到此错误:

SyntaxError: Unexpected token N
    at Object.parse (native)
    at fromJson (http://localhost:3000/assets/angular.js?body=1:803:14)
    at $HttpProvider.defaults.defaults.transformResponse    
http://localhost:3000/assets/angular.js?body=1:9471:18)
    at http://localhost:3000/assets/angular.js?body=1:9446:12
    at Array.forEach (native)
    at forEach (http://localhost:3000/assets/angular.js?body=1:149:11)
    at transformData (http://localhost:3000/assets/angular.js?body=1:9445:3)
    at transformResponse (http://localhost:3000/assets/angular.js?body=1:10061:17)
    at wrappedCallback (http://localhost:3000/assets/angular.js?body=1:7510:59)
    at http://localhost:3000/assets/angular.js?body=1:7583:26 angular.js?body=1:6350
(anonymous function) angular.js?body=1:6350
(anonymous function) angular.js?body=1:5421
wrappedCallback angular.js?body=1:7512
(anonymous function) angular.js?body=1:7583
Scope.$eval angular.js?body=1:8927
Scope.$digest angular.js?body=1:8790
Scope.$apply angular.js?body=1:9013
done angular.js?body=1:10266
completeRequest angular.js?body=1:10450
xhr.onreadystatechange
Run Code Online (Sandbox Code Playgroud)

我正在通过角度执行get()请求,其中json是:

[{"_id":"51f96144c885552bda000015","company_id":"51f82116c88555bf48000004","description":"ENGINEER FOR BEST COMPANY",
"industry_id":null,"location_city":"Pittsburgh","location_coordinates":[-79.9556424,40.4379259],"location_state":"PA","location_zip":"15213","name":"Engineer "},
{"_id":"51f972a5c885552bda000026","company_id":"51f82116c88555bf48000004","description":"has to do everything","industry_id":null,"location_city":"Pittsburgh","location_coordinates":[-79.9418166,40.4443735],"location_state":"PA","location_zip":"15289","name":"job #2"}]
Run Code Online (Sandbox Code Playgroud)

有谁知道这意味着什么?

XML*_*XML 30

任何SyntaxError: Unexpected token意味着你有一些格式错误的JSON,这通常是一个没有用引号括起来的字符串.JSON中仅支持以下数据类型:

  • string(包含在引号中的任何文本)
  • 数组('数组文字',in [])
  • 对象('对象文字',在{})
  • 布尔值(true或者false,不包含在引号中)
  • 整数或数字(不包括在引号中)
  • null(不包括在引号中)

具体来说,SyntaxError: Unexpected token N通常是NaN在JSON 中意外返回a的结果,尽管它可能只是其他一些未包装的字符串.NaN是不是在JSON支持的值,也不是不包裹在引号中,除了任何其它文本true,falsenull(和数字).所以,虽然你null的JSON示例中确实有两个s,但它应该不是问题.(错误中的'N'不是小写的,因为它会在null.)

错误中存在大写字母"N"使我怀疑您NaN在JSON输出中的某处意外返回,即使样本中没有.您样本中唯一的其他大写字母N用引号安全地包装,并且在任何情况下都在字符串的中间.

关键是要确保你正确地清理服务器上的输出,并用零代替任何NaN值,或用引号括起来等.或者,你可以尝试在客户端上处理这样的错误,但它更容易在原点,所以你可以使用条件逻辑来生成内容,而不是需要使用'脏JSON解析器'.(这有点像睡前清理你的地板,而灯仍然亮着,你知道一切都在哪里,而不是需要在黑暗中检测和避免未知的障碍.)


Edd*_*ddy 5

就我而言,使用方法时,json 字符串、键 ( name, age, motto.)没有 用双引号修饰 JSON.parse()

非正式

{
    name: "Jhon Brown",
    age: 30,
    motto: "Please, choose good."
}
Run Code Online (Sandbox Code Playgroud)

会产生如下错误:SyntaxError: Unexpected token n at Object.parse (native)

正式

{
    "name": "Jhon Brwon",
    "age": 30,
    "motto": "Please, choose good."
}
Run Code Online (Sandbox Code Playgroud)