uncaught syntaxerror unexpected token U JSON

Json

Json Problem Overview


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/ . Any help would be appreciated... Thanks.

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"]
]

Json Solutions


Solution 1 - Json

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.

Solution 2 - Json

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;

Solution 3 - Json

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!

Solution 4 - Json

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.

Solution 5 - Json

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

Solution 6 - Json

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.

Solution 7 - Json

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

Solution 8 - Json

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>

Solution 9 - Json

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

Solution 10 - Json

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>

Solution 11 - Json

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!

Solution 12 - Json

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkinath_ruView Question on Stackoverflow
Solution 1 - JsonSean KinseyView Answer on Stackoverflow
Solution 2 - Jsonuser1412699View Answer on Stackoverflow
Solution 3 - JsonKartik ganigaView Answer on Stackoverflow
Solution 4 - JsonMatas VaitkeviciusView Answer on Stackoverflow
Solution 5 - JsonGoodlifeView Answer on Stackoverflow
Solution 6 - JsonSD1985View Answer on Stackoverflow
Solution 7 - JsonRodrigues MafumoView Answer on Stackoverflow
Solution 8 - JsondelliottgView Answer on Stackoverflow
Solution 9 - JsonK PView Answer on Stackoverflow
Solution 10 - Jsonmk MughalView Answer on Stackoverflow
Solution 11 - JsonNancy256View Answer on Stackoverflow
Solution 12 - Jsonuser2605603View Answer on Stackoverflow