[英]SyntaxError: Unexpected token o in JSON at position 1
I'm parsing some data using a type class in my controller.我正在使用 controller 中的 class 类型解析一些数据。 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"
}
I tried to store the data like this我试图像这样存储数据
var userData = _data;
var newData = JSON.parse(userData).data.userList;
How can I extract the user list to a new variable?如何将用户列表提取到新变量?
The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object.您发布的 JSON 看起来不错,但是在您的代码中,它很可能不再是 JSON 字符串,而是已经是 JavaScript 对象。 This means, no more parsing is necessary.
这意味着不再需要解析。
You can test this yourself, eg in Chrome's console:您可以自己测试,例如在 Chrome 的控制台中:
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()
converts the input into a string. JSON.parse()
将输入转换为字符串。 The toString()
method of JavaScript objects by default returns [object Object]
, resulting in the observed behavior. JavaScript 对象的
toString()
方法默认返回[object Object]
,导致观察到的行为。
Try the following instead:请尝试以下操作:
var newData = userData.data.userList;
The first parameter of the JSON.parse
function is expected to be a string, and your data is a JavaScript object, so it will coerce it to the string "[object Object]"
. JSON.parse
函数的第一个参数应该是一个字符串,而你的数据是一个 JavaScript 对象,所以它会将它强制转换为字符串"[object Object]"
。 You should use JSON.stringify
before passing the data:您应该在传递数据之前使用
JSON.stringify
:
JSON.parse(JSON.stringify(userData))
Don't ever use JSON.parse
without wrapping it in try-catch
block:永远不要使用
JSON.parse
而不将其包装在try-catch
块中:
// payload
let userData = null;
try {
// Parse a JSON
userData = JSON.parse(payload);
} catch (e) {
// You can read e for more info
// Let's assume the error is that we already have parsed the payload
// So just return that
userData = payload;
}
// Now userData is the parsed result
就在JSON.parse
上方,使用:
var newData = JSON.stringify(userData)
Unexpected 'O' error is thrown when JSON data or String happens to get parsed.当 JSON 数据或字符串碰巧被解析时,会抛出意外的“O”错误。
If it's string, it's already stringfied.如果它是字符串,则它已经被字符串化了。 Parsing ends up with Unexpected 'O' error.
解析以意外的“O”错误告终。
I faced similar( although in different context), I solved the following error by removing JSON Producer.我遇到了类似的情况(尽管在不同的上下文中),我通过删除 JSON Producer 解决了以下错误。
@POST
@Produces({ **MediaType.APPLICATION_JSON**})
public Response login(@QueryParam("agentID") String agentID , Officer aOffcr ) {
return Response.status(200).entity("OK").build();
}
The response contains "OK" string return.响应包含“OK”字符串返回。 The annotation marked as @Produces({ **MediaType.APPLICATION_JSON })** tries to parse the string to JSON format which results in Unexpected 'O' .
标记为@Produces({ **MediaType.APPLICATION_JSON })** 的注释尝试将字符串解析为 JSON 格式,这会导致Unexpected 'O' 。
Removing @Produces({ MediaType.APPLICATION_JSON }) works fine.删除@Produces({ MediaType.APPLICATION_JSON })工作正常。 Output : OK
输出:好的
Beware: Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'注意:另外,在客户端,如果您发出 ajax 请求并使用 JSON.parse("OK"),它会抛出 Unexpected token 'O'
O is the first letter of the string O是字符串的第一个字母
JSON.parse(object) compares with jQuery.parseJSON(object); JSON.parse(object) 与 jQuery.parseJSON(object) 比较;
JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine
- - 工作正常
We can also add checks like this:我们还可以添加这样的检查:
function parseData(data) {
if (!data) return {};
if (typeof data === 'object') return data;
if (typeof data === 'string') return JSON.parse(data);
return {};
}
You can simply check the typeof userData
& JSON.parse()
it only if it's string
:您可以简单地检查
typeof userData
和JSON.parse()
,仅当它是string
:
var userData = _data;
var newData;
if (typeof userData === 'object')
newData = userData.data.userList; // dont parse if its object
else if (typeof userData === 'string')
newData = JSON.parse(userData).data.userList; // parse if its string
Well, I meant that I need to parse object like this: var jsonObj = {"first name" : "fname"}
.好吧,我的意思是我需要像这样解析对象:
var jsonObj = {"first name" : "fname"}
。 But, I don't actually.但是,我实际上没有。 Because it's already an JSON.
因为它已经是一个 JSON。
Give a try catch like this, this will parse it if its stringified or else will take the default value像这样尝试捕获,如果它的字符串化,这将解析它,否则将采用默认值
let example;
try {
example = JSON.parse(data)
} catch(e) {
example = data
}
first set request value in variable like首先在变量中设置请求值,例如
let reqData = req.body.reqData;让 reqData = req.body.reqData;
if (reqData) {如果(请求数据){
let reqDataValue = JSON.parse(JSON.stringify(reqData)); }
The reason for the error is Object is not in the form of string, it is {}
and it should be string Object( '{}'
)错误原因是 Object 不是字符串形式,是
{}
,应该是字符串 Object( '{}'
)
var data = JSON.parse(userData); var data = JSON.parse(userData); console.log(data);
控制台日志(数据);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.