. Advertisement .
..3..
. Advertisement .
..4..
I am trying to write a programs code that returns the invalid answer. I don’t know where the incorrect command is in the problem – uncaught syntaxerror: unexpected token o in json at position 1. My detail is:
{
"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;
and I end up with the warning message:
uncaught syntaxerror: unexpected token o in json at position 1
Pls, suggest the best answer to fix it.
The cause: The reason is that
JSON.parse()
created a string from the input. While the methodtoString()
of JavaScript objects obviously returns[object Object]
. It is already a JavaScript object, and it does not have any JSON string in the code.Solution: No need to bother about parsing.
Maybe you just check in Chrome’s console:
Your data is a JavaScript object and the first parameter of
JSON.parse
is expected to be string. It will then coerce it into the string"[object Object]"
. Before passing data, you should useJSON.stringify
: