语法错误:JSON 中位置 1 的意外标记 o [英] SyntaxError: Unexpected token o in JSON at position 1
问题描述
我正在使用控制器中的类型类解析一些数据.我得到的数据如下:
I'm parsing some data using a type class in my controller. I'm getting data as follows:
{
"data":{
"userList":[
{
"id":1,
"name":"soni"
}
]
},
"status":200,
"config":{
"method":"POST",
"transformRequest":[
null
],
"transformResponse":[
null
],
"url":"/home/main/module/userlist",
"headers":{
"rt":"ajax",
"Tenant":"Id:null",
"Access-Handler":"Authorization:null",
"Accept":"application/json, text/plain, */*"
}
},
"statusText":"OK"
}
我尝试像这样存储数据
var userData = _data;
var newData = JSON.parse(userData).data.userList;
如何将用户列表提取到新变量中?
How can I extract the user list to a new variable?
推荐答案
您发布的 JSON 看起来不错,但是在您的代码中,它很可能不再是 JSON 字符串,而是已经是 JavaScript 对象.这意味着不再需要解析.
The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary.
您可以自己测试,例如在 Chrome 的控制台中:
You can test this yourself, e.g. in Chrome's console:
new Object().toString()
// "[object Object]"
JSON.parse(new Object())
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse("[object Object]")
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse()
将输入转换为字符串.JavaScript 对象的 toString()
方法默认返回 [object Object]
,导致观察到的行为.
JSON.parse()
converts the input into a string. The toString()
method of JavaScript objects by default returns [object Object]
, resulting in the observed behavior.
尝试以下方法:
var newData = userData.data.userList;
这篇关于语法错误:JSON 中位置 1 的意外标记 o的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!