Error "Uncaught SyntaxError: Unexpected token with JSON.parse" - javascript

What causes this error on the third line?
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products);
var b = JSON.parse(products); //unexpected token o
Open console to view error

products is an object. (creating from an object literal)
JSON.parse() is used to convert a string containing JSON notation into a Javascript object.
Your code turns the object into a string (by calling .toString()) in order to try to parse it as JSON text.
The default .toString() returns "[object Object]", which is not valid JSON; hence the error.

Let's say you know it's valid JSON, but you’re are still getting this...
In that case, it's likely that there are hidden/special characters in the string from whatever source your getting them. When you paste into a validator, they are lost - but in the string they are still there. Those characters, while invisible, will break JSON.parse().
If s is your raw JSON, then clean it up with:
// Preserve newlines, etc. - use valid JSON
s = s.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// Remove non-printable and other non-valid JSON characters
s = s.replace(/[\u0000-\u0019]+/g,"");
var o = JSON.parse(s);

It seems you want to stringify the object, not parse. So do this:
JSON.stringify(products);
The reason for the error is that JSON.parse() expects a String value and products is an Array.
Note: I think it attempts json.parse('[object Array]') which complains it didn't expect token o after [.

I found the same issue with JSON.parse(inputString).
In my case, the input string is coming from my server page (return of a page method).
I printed the typeof(inputString) - it was string, but still the error occurs.
I also tried JSON.stringify(inputString), but it did not help.
Later I found this to be an issue with the new line operator [\n], inside a field value.
I did a replace (with some other character, put the new line back after parse) and everything was working fine.

JSON.parse is waiting for a String in parameter. You need to stringify your JSON object to solve the problem.
products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
console.log(products);
var b = JSON.parse(JSON.stringify(products)); //solves the problem

You should validate your JSON string here.
A valid JSON string must have double quotes around the keys:
JSON.parse({"u1":1000,"u2":1100}) // will be ok
If there are no quotes, it will cause an error:
JSON.parse({u1:1000,u2:1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
Using single quotes will also cause an error:
JSON.parse({'u1':1000,'u2':1100})
// error Uncaught SyntaxError: Unexpected token ' in JSON at position 1

products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
change to
products = '[{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}]';

If there are leading or trailing spaces, it'll be invalid.
Trailing and leading spaces can be removed as
mystring = mystring.replace(/^\s+|\s+$/g, "");
Source: JavaScript: trim leading or trailing spaces from a string

Here's a function I made based on previous replies: it works on my machine but YMMV.
/**
* #description Converts a string response to an array of objects.
* #param {string} string - The string you want to convert.
* #returns {array} - an array of objects.
*/
function stringToJson(input) {
var result = [];
// Replace leading and trailing [], if present
input = input.replace(/^\[/, '');
input = input.replace(/\]$/, '');
// Change the delimiter to
input = input.replace(/},{/g, '};;;{');
// Preserve newlines, etc. - use valid JSON
//https://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse
input = input.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// Remove non-printable and other non-valid JSON characters
input = input.replace(/[\u0000-\u0019]+/g, "");
input = input.split(';;;');
input.forEach(function(element) {
//console.log(JSON.stringify(element));
result.push(JSON.parse(element));
}, this);
return result;
}

One other gotcha that can result in "SyntaxError: Unexpected token" exception when calling JSON.parse() is using any of the following in the string values:
New-line characters.
Tabs (yes, tabs that you can produce with the Tab key!)
Any stand-alone slash \ (but for some reason not /, at least not on Chrome.)
(For a full list see the String section here.)
For instance the following will get you this exception:
{
"msg" : {
"message": "It cannot
contain a new-line",
"description": "Some discription with a tabbed space is also bad",
"value": "It cannot have 3\4 un-escaped"
}
}
So it should be changed to:
{
"msg" : {
"message": "It cannot\ncontain a new-line",
"description": "Some discription with a\t\ttabbed space",
"value": "It cannot have 3\\4 un-escaped"
}
}
Which, I should say, makes it quite unreadable in JSON-only format with larger amount of text.

My issue was that I had commented HTML in a PHP callback function via Ajax that was parsing the comments and return invalid JSON.
Once I removed the commented HTML, all was good and the JSON was parsed without any issues.

When you are using the POST or PUT method, make sure to stringify the body part.
I have documented an example here at
https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154

[
{
"name": "Pizza",
"price": "10",
"quantity": "7"
},
{
"name": "Cerveja",
"price": "12",
"quantity": "5"
},
{
"name": "Hamburguer",
"price": "10",
"quantity": "2"
},
{
"name": "Fraldas",
"price": "6",
"quantity": "2"
}
]
Here is your perfect JSON content that you can parse.

The only mistake is you are parsing an already-parsed object, so it's throwing an error. Use this and you will be good to go.
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products[0].name); // Name of item at 0th index
If you want to print the entire JSON content, use JSON.stringify().

products is an array which can be used directly:
var i, j;
for(i=0; i<products.length; i++)
for(j in products[i])
console.log("property name: " + j, "value: " + products[i][j]);

Now apparently \r, \b, \t, \f, etc. aren't the only problematic characters that can give you this error.
Note that some browsers may have additional requirements for the input of JSON.parse.
Run this test code in your browser:
var arr = [];
for(var x=0; x < 0xffff; ++x){
try{
JSON.parse(String.fromCharCode(0x22, x, 0x22));
}catch(e){
arr.push(x);
}
}
console.log(arr);
Testing on Chrome, I see that it doesn't allow JSON.parse(String.fromCharCode(0x22, x, 0x22)); where x is 34, 92, or from 0 to 31.
Characters 34 and 92 are the " and \ characters respectively, and they are usually expected and properly escaped. It's characterss 0 to 31 that would give you problems.
To help with debugging, before you do JSON.parse(input), first verify that the input doesn't contain problematic characters:
function VerifyInput(input){
for(var x=0; x<input.length; ++x){
let c = input.charCodeAt(x);
if(c >= 0 && c <= 31){
throw 'problematic character found at position ' + x;
}
}
}

Oh man, solutions in all previous answers didn't work for me. I had a similar problem just now. I managed to solve it with wrapping with the quote. See the screenshot. Whoo.
Original:
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products);
var b = JSON.parse(products); //unexpected token o

The error you are getting, i.e., "unexpected token o", is because JSON is expected, but an object is obtained while parsing. That "o" is the first letter of word "object".

It can happen for a lot of reasons, but probably for an invalid character, so you can use JSON.stringify(obj); that will turn your object into a JSON, but remember that it is a jQuery expression.

In my case there are the following character problems in my JSON string:
\r
\t
\r\n
\n
:
"
I have replaced them with other characters or symbols, and then reverted back again from coding.

This is now a JavaScript array of objects, not JSON format. To convert it into JSON format, you need to use a function called JSON.stringify().
JSON.stringify(products)

Why do you need JSON.parse? It's already in an array-of-object format.
Better use JSON.stringify as below:
var b = JSON.stringify(products);

The mistake I was doing was passing null (unknowingly) into JSON.parse().
So it threw Unexpected token n in JSON at position 0.
But this happens whenever you pass something which is not a JavaScript Object in JSON.parse().

Use eval. It takes JavaScript expression/code as string and evaluates/executes it.
eval(inputString);

Related

Convert normal String to Object in JavaScript?

I am getting this String as input
"countries" : "[[england, australia], [UAE, China], [UAE]]"
Requirement
I thought that, I need to transform this String into
{"countries": [["england", "australia"], ["UAE", "China"], ["UAE"]]}
Then I can convert it to Object in js using json.parse() method.
I tried various things but none seem to work.
I Tried
JSON.stringify
JSON.parse
eval
I have done this in Java but in Javascript not able to do so.
I am new to js, as in java I can easily do this JSONObject.
Any help will be appreciated, Thanks !!
This requires multiple steps:
Wrap the input in curly braces and do a JSON.parse:
const input = "\"countries\" : \"[[england, australia], [UAE, China], [UAE]]\""
const result = JSON.parse("{" + input + "}")
That gives you an object like:
{
"countries": "[[england, australia], [UAE, China], [UAE]]"
}
Then wrap the inner strings with double quotes and parse it again:
const inner = result.countries
result.countries = JSON.parse(inner.replaceAll(/([a-zA-Z]+)/g, '"$1"'))
That gives you result:
{
"countries": [
[
"england",
"australia"
],
[
"UAE",
"China"
],
[
"UAE"
]
]
}

How to convert JSON object to a different format [duplicate]

This question already has answers here:
JSON.stringify without quotes on properties?
(16 answers)
Closed 3 years ago.
I have a JSON object like this
{
"name": "Test Name",
"age": 24
}
Is there a way I can convert this to a String in a format like
{
name: "Test Name",
age: 24
}
The JSON will be of varying lengths with different properties.
Right now, I am doing this as shown below. This can get too long and messy for larger and more complex JSON objects. I need to know if there is an easier and cleaner solution for this.
let cypherQueryObject = '{';
cypherQueryObject += ` name: "${user.name}";
if (user.age) { cypherQueryObject += `, age: "${user.age}"` };
cypherQueryObject = '}';
The solution that you are looking for is little different than what someone expect. JavaScript's JSON.stringify() generates JSON string and a valid JSON contains " (double quotes only) around keys.
In your case, you are trying to use the JSON string without " around keys. So here is a little simple process to do that. Here I am assuming that you are going to use this in simple kind of JSON strings where the value part of any key don't have key: kind of things then it will work fine of bigger JSONs too.
If it is not like that then you will need to improve the find & replace utility in more efficient form. Regular expressions are great for this work.
Here I have tried to solve your problem like this.
I have used NODE REPL to execute statements so please ignore undefined returned by default.
>
> let o = {
... "name": "Test Name",
... "age": 24
... }
undefined
>
> s = JSON.stringify(o)
'{"name":"Test Name","age":24}'
>
> s = JSON.stringify(o, undefined, 4)
'{\n "name": "Test Name",\n "age": 24\n}'
>
> console.log(s)
{
"name": "Test Name",
"age": 24
}
undefined
>
> for(k in o) {
... s = s.replace("\"" + k + "\":", k + ':')
... }
'{\n name: "Test Name",\n age: 24\n}'
>
> console.log(s)
{
name: "Test Name",
age: 24
}
undefined
>
you can have a look at this as well.

JSON Throwing Error on Parsing

Here is the JSON String I have. I have removed the opening and closing brackets from the JSON because I need to use the JSON values in jQuery to actually load the data in a select box:
{
"text": "Pediatric FA, CPR & AED (2015)",
"id": "128177000002431552~Pediatric FA, CPR & AED DVD Set (2015)~YES~117.19"
}, {
"text": "FA, CPR & AED Manual (2015)",
"id": "128177000002431564~FA, CPR & AED Manual (2015)~YES~17.73"
}
here is my Javascript Code
$.post("items.cfm",{"term":request.term})
.done(function(data){
try{
var obj = JSON.parse(data),
values = [];
$.each(data, function(i, obj) {
values.push({"label":obj[x].text, "value":obj[x].id, "price":obj[x].id.split('~')[3]});
})
response(values);
}catch(e){
alert(e);
}
})
.fail(function(e){
alert(e);
});
every time I run it I am getting the error
SyntaxError: Unexpected token , in JSON at position
You have two JSON objects separated by a comma. If you meant this to be an array, you need to surround it with array brackets:
[
{
"text": "Pediatric FA, CPR & AED (2015)",
"id": "128177000002431552~Pediatric FA, CPR & AED DVD Set (2015)~YES~117.19"
}, {
"text": "FA, CPR & AED Manual (2015)",
"id": "128177000002431564~FA, CPR & AED Manual (2015)~YES~17.73"
}
]
As a side note, if your server is generating invalid JSON, you should take a good look at the code that's producing the JSON. Chances are, there's code trying to generate this string by hand, which is a bad practice. The server should be using a library to convert the returned value into JSON.

What goes wrong if 77>602?

What goes wrong if 77>602? I tried in IE, Firefox and Chrome
function getMaxValue(data){
var maxValue=0;
for(var i=0;i<data.length;i++){
if(data[i].value>maxValue){
console.log(data[i].value +">"+maxValue);
maxValue=data[i].value;
}
}
console.log("MaxValue:"+maxValue);
return maxValue;
}
I get my data from a json:
[{
"keyword": "User: Allen-P",
"value": "602"
}, {
"keyword": "From: phillip.allen#enron.com",
"value": "598"
},
{
"keyword": "Date: 2001",
"value": "276"
},
{
"keyword": "Subject: Re:",
"value": "228"
},
{
"keyword": "Date: 2001 Apr",
"value": "77"
},
]
Needed to add some useless description for StackOverflow. Please help me;). The json file is a bit bigger and just an example.
Strings are compared alphabetically even if they contain numbers. The character '7' comes after the character '6', alphabetically, so indeed, in terms of strings, "77" > "602".
The solution is to convert them to numbers first:
if(parseFloat(data[i].value) > maxValue){
Or for sake of brevity, the unary + operator will also do this:
if(+data[i].value > maxValue){
You're currently comparing an integer with a string, which doesn't reliably work in this situation.
Either change your JSON and unquote the values, or use the following code instead:
function getMaxValue(data){
var maxValue=0;
for(var i=0;i<data.length;i++){
if(parseInt(data[i].value) > maxValue) {
console.log(data[i].value +">"+maxValue);
maxValue=data[i].value;
}
}
console.log("MaxValue:"+maxValue);
return maxValue;
}
Also read this for reference.
You need to use parseInt(value,10) to convert the value from a string to a number

ExtJS decode method fails to decode "&quot" After File Upload

I have a JSON format result sent back to the client that hold the $quot sign. for some unknown reason the code breaks.
Here is the code that bricks from ext-all-debug:
doDecode = function(json){
return eval("(" + json + ")"); FAILS HERE
},
Here is my JSON as it left the server (As far as I know , I hope the server doesn't take the time to decode this &quot on its free time.):
{
success: true,
total: 1,
results: [{
"ID": -1,
"Value": "POChangeRequestlblCustomerCatalogNumber",
"Description": "",
"Labels": {
"1": {
"ID": -1,
"LanguageID": 1,
"Value": "Catalog Number",
"ToolTip": "",
"LanguageName": "English",
"KeyID": -1,
"KeyValue": "POChangeRequestlblCustomerCatalogNumber",
"KeyDescription": ""
},
"2": {
"ID": -1,
"LanguageID": 2,
"Value": """, <<< THIS IS THE BAD PART!!!
"ToolTip": "",
"LanguageName": "Hebrew",
"KeyID": -1,
"KeyValue": "POChangeRequestlblCustomerCatalogNumber",
"KeyDescription": ""
}
},
"ServerComments": "1"
}]
}
this JSON is sent in a text/html content type as it is the result of a file upload operation. could that be part of the problem?
Ok, I have continued to trace down the problem and found that ExtJS does this function on the returned value from a hidden iframe:
doFormUpload : function(o, ps, url){
...
try{
doc = frame.contentWindow.document || frame.contentDocument || WINDOW.frames[id].document;
if(doc){
if(doc.body){
if(/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)){
r.responseText = firstChild.value;
}else{
r.responseText = doc.body.innerHTML; << THIS IS WHERE MY " get decoded back to " (sign)
}
}
r.responseXML = doc.XMLDocument || doc;
}
}
catch(e) {}
...
}
Is there a good workaround for this issue. it seems that the browser automatically decodes the value???? any one???? this is a major issue !!
Here is how I worked around it.
The problem was that all browsers automatically decode the & quot; signs.
So I have fixed the Ext doFormUpload function to look like this:
doFormUpload : function(o, ps, url){
...
try{
doc = frame.contentWindow.document || frame.contentDocument || WINDOW.frames[id].document;
if(doc){
if(doc.body){
if(doc.body.innerText){
r.responseText = doc.body.innerText;
}else{
r.responseText = doc.body.innerHTML.replace(/<pre>/ig,'').replace(/<\/pre>/ig,'');
}
}
r.responseXML = doc.XMLDocument || doc;
}
}
catch(e) {}
...
}
In addition from now on the content type that the server is returning is "text/plain"
this prevents the browsers from decoding the data.
I also added a little workaround from FF that does not support innerText property but adds the tag that wraps the response.
This is an ugly hack to the ExJS framwork but it worked for me.
Hopefully someone will notice the question and have some better idea on how to solve it.
It doesn't look like the encoded quote is causing your issue -- take a look at this jsfiddle to see that the Ext.decode function works perfectly fine when decoding a JSON string containing ":
http://jsfiddle.net/MXVvR/
Are you sure that the server is returning a JSON string and not a JSON object? Inspect the server response using Firebug, Fiddler, or Chrome Developer Tools to see exactly what's coming back from the server.

Categories

Resources