SyntaxError: Unexpected token o in JSON at position 1 - javascript

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"
}
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. This means, no more parsing is necessary.
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() converts the input into a string. The toString() method of JavaScript objects by default returns [object Object], resulting in the observed behavior.
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]". You should use JSON.stringify before passing the data:
JSON.parse(JSON.stringify(userData))

Don't ever use JSON.parse without wrapping it in try-catch block:
// 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

Just above JSON.parse, use:
var newData = JSON.stringify(userData)

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:
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

Unexpected 'O' error is thrown when JSON data or String happens to get parsed.
If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.
I faced similar( although in different context), I solved the following error by removing 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.
The annotation marked as #Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.
Removing #Produces({ MediaType.APPLICATION_JSON}) works fine.
Output : OK
Beware:
Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'
O is the first letter of the string
JSON.parse(object) compares with jQuery.parseJSON(object);
JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine

The reason for the error is Object is not in the form of string, it is {} and it should be string Object('{}')

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;
if (reqData) {
let reqDataValue = JSON.parse(JSON.stringify(reqData));
}

Related

Why it works like this? [duplicate]

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"
}
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. This means, no more parsing is necessary.
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() converts the input into a string. The toString() method of JavaScript objects by default returns [object Object], resulting in the observed behavior.
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]". You should use JSON.stringify before passing the data:
JSON.parse(JSON.stringify(userData))
Don't ever use JSON.parse without wrapping it in try-catch block:
// 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
Just above JSON.parse, use:
var newData = JSON.stringify(userData)
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:
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
Unexpected 'O' error is thrown when JSON data or String happens to get parsed.
If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.
I faced similar( although in different context), I solved the following error by removing 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.
The annotation marked as #Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.
Removing #Produces({ MediaType.APPLICATION_JSON}) works fine.
Output : OK
Beware:
Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'
O is the first letter of the string
JSON.parse(object) compares with jQuery.parseJSON(object);
JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine
The reason for the error is Object is not in the form of string, it is {} and it should be string Object('{}')
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;
if (reqData) {
let reqDataValue = JSON.parse(JSON.stringify(reqData));
}

Can't get the value of json object

I have this json object, and i want to get the value of the error but it always returning me an undefined result.
Here is the json object
{"isValid":false,"errors":["Username is required.","Password is required."]}
my code is:
success: function (response) {
var JSONstring = JSON.stringify(response);
var JSONobject = JSON.parse(JSONstring);
alert(JSONstring);
alert(JSONobject);
console.log(JSONobject);
var _result = JSONobject.errors;
i have also tried:
var _result = JSONobject[0]['errors'];
var _result = JSONobject['errors'][0];
but still i can't access the value.
If you already have access to the JSON object you can work with it without manipulation. If your question was also looking to get it in that form, see this StackOverflow answer for how to format your request.
success: function (response) {
// Assuming response = {"isValid":false,"errors":["Username is required.","Password is required."]}
// Directly access the property errors
var errors = response.errors;
console.log(errors); // ["Username is required.","Password is required."]
JSFiddle

Unable to access JSON Element in Javascript via Object.property

I am unable to access a simple JSON Element from a JSON Structure that looks like:
{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}
I get the data in JSON Format but when i do data.ACTION or data.MESSAGE i get Undefined as the output.
By doing case sensitive also, its not working( Image attached )
var url = base + query;
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(url).then(function (data) {
console.log(data); //Getting JSON Data
var output = JSON.stringify(data);
var obj = JSON.parse(output.replace(/ 0+(?![\. }])/g, ' '));
console.log(output);
console.log(obj.message); //Here getting UNDEFINED
}, function (status) { //error detection....
alert('Something went wrong.');
});
Console:
{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}
stringify returns the following
{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}"
EDITED. I first thought the error was due to parsing, given the print. -.-
Solution:
When you print the output, obj it's still a string, not an object. So it is OK at that point.
Your "undefined" property message should be replaced by MESSAGE.
Instead of console.log(obj.message); just use console.log(obj.MESSAGE);
Also. An example of parsing JSON:
var myJson = '{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}';
console.log(myJson); // This prints the literal string
console.log(JSON.parse(myJson)); // this prints an "object"
obj.message property is not defined and when you try to get the property which is not defined on an object, you get undefined.
Javascript is case sensitive. You should try obj.MESSAGE instead to get the property value. Also, to check if a property exists on an object you can make use of object.hasOwnProperty([propName]) method to check if a property exists on a object or not.
EDIT 1: Try running the following code snippet. JSON data string is parsed before accessing the property.
var jsonString = "{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}";
var obj = JSON.parse(jsonString);
console.log(obj.MESSAGE);
data already is a JSON string, there's no need to JSON.stringify it (which returns a string with a JSON-encoded string literal). Parsing it into output only leads to a string again, which has no properties. You should use
console.log(data);
var obj = JSON.parse(data);
console.log(obj);
obj.MESSAGE = obj.MESSAGE.replace(/ 0+(?![\. }])/g, ' ');
(notice the proper casing of the property name)
You can try:
var jsonObject = data.data;
console.log(jsonObject.ACTION)

JSON.parse parsing a string into string

I have confusion over the functionality of JSON.parse.
I am writing code :
dynamicMsgObj = '"rest, no disc"';
var jsonObj = {};
var isJsonString = function isJsonString(str) {
try {
jsonObj = JSON.parse(str);
} catch (e) {
return false;
}
return true;
}(dynamicMsgObj);
console.log(isJsonString);// returns true
console.log(typeof jsonObj);//returns string
How is this happening??
In this way I can't determine if I am receiving string or object, which is my main objective.
Please help
That's because JSON.parse is able to successfully parse that input, it will parse it as a string and a string is what the return result will be.
Check out the documentation and look at the examples. This one specifically:
JSON.parse('"foo"'); // "foo"
And in regards to achieving your objective, you have done that already:
if(isJsonString && typeof jsonObj == 'string')
// is string
else
// is something else

JSON anonymous type property undefined?

in my mvc3 roject, I return the Json object:
return Json(new { ID = guid, FileName = file.FileName, FullPath = filename });
then, in the JS code, I try to acces to the fields, e.g:
onComplete: function (event, queueId, fileObj, response, data) {
alert(response.ID); //test
}
but i get the undefined message. If i just get the alert(response); I see the valid object:
{"ID":"22186ea1-a56a-45d1-9d13-d19f003dedf9","FileName":"file.txt","FullPath":"some_path"}
so how to access to that properties ?
You're probably seeing the JSON text that needs to be parsed into JavaScript data structures.
var parsed = JSON.parse(response);
alert( parsed.ID );
Without parsing it, you're trying to access the ID property of a String object.
var str = '{"ID":"22186ea1-a56a-45d1-9d13-d19f003dedf9","FileName":"file.txt","FullPath":"some_path"}';
alert( str.ID ); // undefined

Categories

Resources