简体   繁体   中英

Uncaught SyntaxError: Unexpected token with JSON.parse

what causes this error on the third line?

products<\/code> is an object. (creating from an object literal)


The default .toString()<\/code> returns "[object Object]"<\/code> , which is not valid JSON; hence the error.

Let's say you know it's valid JSON but your are still getting this...

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()<\/code>

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

It seems you want to stringify<\/strong> the object, not parse. So do this:

JSON.stringify(products);

I found the same issue with JSON.parse(inputString)<\/code> .

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

JSON.parse({"u1":1000,"u2":1100})       // will be ok
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\/Leading spaces can be removed as

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

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"<\/code> exception when calling JSON.parse()<\/code> is using any of the following in the string values:

  1. "

[
  {
    "name": "Pizza",
    "price": "10",
    "quantity": "7"
  },
  {
    "name": "Cerveja",
    "price": "12",
    "quantity": "5"
  },
  {
    "name": "Hamburguer",
    "price": "10",
    "quantity": "2"
  },
  {
    "name": "Fraldas",
    "price": "6",
    "quantity": "2"
  }
]

Hopefully this helps someone else.

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

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.

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<\/code> , \\b<\/code> , \\t<\/code> , \\f<\/code> , etc aren't the only problematic chars that can give you this error.

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

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.

The error you are getting ie "unexpected token o" is because json is expected but 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 char, so you can use JSON.stringify(obj);<\/code> that will turn your object into a JSON but remember that it is a JQUERY expression.

"

I have this error BECAUSE the API that returned the json object was giving AN ERROR (in my case Code Igniter, return an html when the php code fails) so IT'S NOT AN JSON OBJECT.

Check the SQL Sentences and the PHP code, and test it with Postman (or some other API tester)

In my case there is following character problems in my JSON<\/code> string

  1. <\/li>
  2. <\/li>
  3. <\/li>
  4. <\/li>
  5. <\/li>
  6. <\/li><\/ol>

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

    "

This is now a JavaScript Array of Object, not JSON format. TO convert it into JSON format you need to use a function called JSON.stringify()<\/strong>

JSON.stringify(products)

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

The mistake I was doing was passing null<\/code> (unknowingly) into JSON.parse().

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

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

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

eval(inputString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM