[javascript] Uncaught SyntaxError: Unexpected token with JSON.parse

what causes this error on the third line?

_x000D_
_x000D_
var products = [{_x000D_
  "name": "Pizza",_x000D_
  "price": "10",_x000D_
  "quantity": "7"_x000D_
}, {_x000D_
  "name": "Cerveja",_x000D_
  "price": "12",_x000D_
  "quantity": "5"_x000D_
}, {_x000D_
  "name": "Hamburguer",_x000D_
  "price": "10",_x000D_
  "quantity": "2"_x000D_
}, {_x000D_
  "name": "Fraldas",_x000D_
  "price": "6",_x000D_
  "quantity": "2"_x000D_
}];_x000D_
console.log(products);_x000D_
var b = JSON.parse(products); //unexpected token o
_x000D_
_x000D_
_x000D_

Open console to view error

This question is related to javascript jquery json

The answer is


When you are using POST or PUT method, make sure to stringify the body part.

I have documented an example here https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154


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]);

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

  1. New-line characters.

  2. Tabs (yes, tabs that you can produce with the Tab key!)

  3. 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.


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


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, 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 is working fine.


Why you need JSON.parse? It's already in array of object format.

Better use JSON.stringify as below : var b = JSON.stringify(products);

This may help you.


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

In my case there is following character problems in my JSON string

  1. \r
  2. \t
  3. \r\n
  4. \n
  5. :
  6. "

I have replaced them with another characters or symbols, and then revert back again from coding.


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


[
  {
    "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 that you can parse.


It seems you want to stringify the object. 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 [.


Now apparently \r, \b, \t, \f, etc aren't the only problematic chars that can give you this error.

Note that some browsers may have additional requirements for the input of JSON.parse.

Run this test code on 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.

Chars 34 and 92 are the " and \ characters respectively, and they are usually expected and properly escaped. It's chars 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;
        }
    }
}

JSON.parse() deals with strings, but your products are objects. You need to convert them into strings.

Also, make sure that your json format is correct, and there can be no format errors, otherwise there will be exceptions. You can use some online sites to verify JSON Formatter


Use eval. It takes JavaScript expression/code as string and evaluates/executes it.

eval(inputString);

The only mistake you are doing is, you are parsing already parsed object so it's throwing error, use this and you will be good to go.

_x000D_
_x000D_
var products = [{_x000D_
  "name": "Pizza",_x000D_
  "price": "10",_x000D_
  "quantity": "7"_x000D_
}, {_x000D_
  "name": "Cerveja",_x000D_
  "price": "12",_x000D_
  "quantity": "5"_x000D_
}, {_x000D_
  "name": "Hamburguer",_x000D_
  "price": "10",_x000D_
  "quantity": "2"_x000D_
}, {_x000D_
  "name": "Fraldas",_x000D_
  "price": "6",_x000D_
  "quantity": "2"_x000D_
}];_x000D_
console.log(products[0].name); //name of item at 0th index
_x000D_
_x000D_
_x000D_

if you want to print entire json then use JSON.stringify()


Let's say you know it's valid JSON but your 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 chars, 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 chars
s = s.replace(/[\u0000-\u0019]+/g,""); 
var o = JSON.parse(s);

If there are leading or trailing spaces, it'll be invalid. Trailing/Leading spaces can be removed as

mystring = mystring.replace(/^\s+|\s+$/g, "");

Source: http://www.toptip.ca/2010/02/javascript-trim-leading-or-trailing.html


Check this code. It gives you the clear solution of JSON parse error. It commonly happen by the newlines and the space between json key start and json key end

data_val = data_val.replace(/[\n\s]{1,}\"/g, "\"")  
               .replace(/\"[\n\s]{1,}/g, "\"")  
               .replace(/[\n]/g, "\\n") 

The mistake I was doing was passing null (unknowingly) into JSON.parse().

So it threw Unexpected token n in JSON at position 0


Hopefully this helps someone else.

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 with no issues.


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"}]';

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

Oh man, solutions in all above answers provided so far 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.

enter image description here

Original:

_x000D_
_x000D_
var products = [{_x000D_
  "name": "Pizza",_x000D_
  "price": "10",_x000D_
  "quantity": "7"_x000D_
}, {_x000D_
  "name": "Cerveja",_x000D_
  "price": "12",_x000D_
  "quantity": "5"_x000D_
}, {_x000D_
  "name": "Hamburguer",_x000D_
  "price": "10",_x000D_
  "quantity": "2"_x000D_
}, {_x000D_
  "name": "Fraldas",_x000D_
  "price": "6",_x000D_
  "quantity": "2"_x000D_
}];_x000D_
console.log(products);_x000D_
var b = JSON.parse(products); //unexpected token o
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?