327

I get this error "uncaught syntaxerror unexpected token U" when I run my page in chrome. And in firefox I get, "JSON.parse: unexpected character". I'm returning the json data from a php file and the returning json string is valid. I checked it with http://jsonlint.com/.

Here's the returned JSON string

[ ["1","Pan Africa Market","\"1521 1st Ave, Seattle, WA\"","47.608941","-122.340145","restaurant"], ["2","The Melting Pot","14 Mercer St, Seattle, WA","47.624562","-122.356442","restaurant"], ["3","Ipanema Grill","1225 1st Ave, Seattle, WA","47.606366","-122.337656","restaurant"], ["4","Sake House","230 1st Ave, Seattle, WA","47.612825","-122.34567","bar"], ["5","Crab Pot","1301 Alaskan Way, Seattle, WA","47.605961","-122.34036","restaurant"], ["6","Mexican Kitchen","2234 2nd Ave, Seattle,WA","47.613975","-122.345467","bar"], ["7","Wingdome","1416 E Olive Way, Seattle, WA","47.617215","-122.326584","bar"], ["8","Piroshky Piroshky","1908 Pike pl, Seattle, WA","47.610127","-122.342838","restaurant"] ] 
3
  • Can you post the JSON? When I get that error it typically manes that there is an un-terminated string - it is indicating that it is at the letter 'U' in the JSON. Commented Oct 23, 2012 at 1:03
  • Could be some strange problem with the \" in the output. Commented Oct 23, 2012 at 1:14
  • That JSON parses fine. You should try to figure out what your code is actually choking on. Commented Oct 23, 2012 at 2:12

13 Answers 13

706

That error is normally seen when the value given to JSON.parse is actually undefined. So, I would check the code that is trying to parse this - most likely you are not parsing the actual string shown here.

Sign up to request clarification or add additional context in comments.

7 Comments

It might also be "undefined" as a string instead of the literal undefined. I just spent 30 minutes finding that out.
@ns47731 That is actually the same. The reason why an actual undefined becomes u, is that undefined is coerced into a string (because a string is what JSON.parse expects).
Ugh, was sending an asynchronous request and immediately trying to parse the undefined return. Disgusted with myself, thanks.
This error would also be throwed trough a UTF-8{" at the beginning of the json string
My error was Unexpected token N in JSON at position... and the problem was a double value: NaN
|
14

I was getting this message while validating (in MVC project). For me, adding ValidationMessageFor element fixed the issue.

To be precise, line number 43 in jquery.validate.unobtrusive.js caused the issue:

 replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false; 

1 Comment

This got me on the right track; in my case I was doing $("form :input").valid(); to trigger validation. But apparently it got an error on a hidden field without a ValidationMessageFor. Fixed by changing to $("form :input:visible").valid();
12

The parameter for the JSON.parse may be returning nothing (i.e. the value given for the JSON.parse is undefined)!

It happened to me while I was parsing the Compiled solidity code from an xyz.sol file.

import web3 from './web3'; import xyz from './build/xyz.json'; const i = new web3.eth.Contract( JSON.parse(xyz.interface), '0x99Fd6eFd4257645a34093E657f69150FEFf7CdF5' ); export default i; 

which was misspelled as

JSON.parse(xyz.intereface) 

which was returning nothing!

Comments

5

Most common case of this error happening is using template that is generating the control then changing the way id and/or nameare being generated by 'overriding' default template with something like

@Html.TextBoxFor(m => m, new {Name = ViewData["Name"], id = ViewData["UniqueId"]} ) 

and then forgetting to change ValidationMessageFor to

@Html.ValidationMessageFor(m => m, null, new { data_valmsg_for = ViewData["Name"] }) 

Hope this saves you some time.

Comments

3

Just incase u didnt understand

e.g is that lets say i have a JSON STRING ..NOT YET A JSON OBJECT OR ARRAY.

so if in javascript u parse the string as

var body={ "id": 1, "deleted_at": null, "open_order": { "id": 16, "status": "open"} var jsonBody = JSON.parse(body.open_order); //HERE THE ERROR NOW APPEARS BECAUSE THE STRING IS NOT A JSON OBJECT YET!!!! //TODO SO var jsonBody=JSON.parse(body)//PASS THE BODY FIRST THEN LATER USE THE jsonBody to get the open_order var OpenOrder=jsonBody.open_order; 

Great answers above

Comments

3

I experienced this error when I ran a find condition on a JSONArray within a for loop. The problem I faced was the result of one of the values in the for loop returning null. Hence, when I tried to access a property on that it failed.

So if you are doing anything within JSONArrays where you are not sure of the data source and its integrity I thinks its a good habit to deal with null and undefined exceptions in this case.

I fixed it by checking for null on the returned value of find on the JSONArray and handling exceptions appropriately.

Thought this might help.

Comments

3

is so simple to resolve that error.

The Cause. Javascript is giving that error because you are parsing empty string, object or array.

Resolution so to solve that, just check if the string your are trying to parse is empty/null ou not. if is not empty/null you can parse that string.

let ParsedString; if(yourString != null){ ParsedString = JSON.parse(yourString); } 

Comments

1

In my case it was trying to call JSON.parse() on an AJAX variable before the XHRResponse came back. EG:

var response = $.get(URL that returns a valid JSON string); var data = JSON.parse(response.responseText); 

I replaced that with an example out of the jQuery site for $.get:

<script type="text/javascript"> var jqxhr = $.get( "https://jira.atlassian.com/rest/api/2/project", function() { alert( "success" ); }) .done(function() { //insert code to assign the projects from Jira to a div. jqxhr = jqxhr.responseJSON; console.log(jqxhr); var div = document.getElementById("products"); for (i = 0; i < jqxhr.length; i++) { console.log(jqxhr[i].name); div.innerHTML += "<b>Product: " + jqxhr[i].name + "</b><BR/>Key: " + jqxhr[i].key + "<BR/>"; } console.log(div); alert( "second success" ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "finished" ); }); // Perform other work here ... // Set another completion function for the request above jqxhr.always(function() { alert( "second finished" ); }); </script> 

Comments

1

Well, to all who actually can't find the error anywhere in your code, neither "undefined as it says in local storage nor null"..simply just comment out your code and write another one that actually removes the item in local storage ..after that ,u can comment or delet the current code and reset again the previous one by simply uncommenting it out (if u dint delet t ...if u did u can write it again:))

LocalStorage.setItem('Previous' , "removeprevious"); LocalStorage.removeItem('Previous'); Console.log(LocalStorage.getItem('Previous')); 

Console will show null and that it ..reset your code again if t doesn't work, dude!you got errors.

sorry for my English!

Comments

1

This answer can be a possible solution from many. This answer is for the people who are facing this error while working with File Upload..

We were using middleware for token based encryption - decryption and we encountered same error.

Following was our code in route file:

 router.route("/uploadVideoMessage") .post( middleware.checkToken, upload.single("video_file"), videoMessageController.uploadVideoMessage ); 

here we were calling middleware before upload function and that was causing the error. So when we changed it to this, it worked.

router.route("/uploadVideoMessage") .post( upload.single("video_file"), middleware.checkToken, videoMessageController.uploadVideoMessage ); 

Comments

0

This is not a difficult task. That problem also occur at my site you should have to shift your js files top ordered. Because at the place where you are using JSON Parsing, this time your JS files are not loaded. EXAMPLE #

<script type="text/javaScript"> ...........SOME CODE............. </script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 

change to

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script type="text/javaScript"> ...........SOME CODE............. </script> 

Comments

0

You should consider trying to parse the data on the server side and then send it to the client to work with it.

Comments

-3

I was getting this error, when I was using the same variable for json string and parsed json:

var json = '{"1":{"url":"somesite1","poster":"1.png","title":"site title"},"2":{"url":"somesite2","poster":"2.jpg","title":"site 2 title"}}' function usingjson(){ var json = JSON.parse(json); } 

I changed function to:

function usingjson(){ var j = JSON.parse(json); } 

Now this error went away.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.