Unexpected Token while Parsing JSON - javascript

This is fraustating me for 5 hours and now i have to finally ask this question.
I am trying to parse JSON using Javascript, but i don't know why i am getting this error on Console:
Uncaught SyntaxError: Unexpected token (…)
(anonymous function) # VM382:2InjectedScript._evaluateOn #
VM251:904InjectedScript._evaluateAndWrap # VM251:837InjectedScript.evaluate
#VM251:693
JSON : http://pastebin.com/DddXQj6d
JS Code:
var json=**big json**;
var obj=JSON.parse(json);
Tried:
JSON.stringify(json);
json= "'" + json+ "'";
Loading JSON from URL

According to JSONLint and the Pastebin that you posted, the JSON is invalid, mostly due to the use of \'. Once you replace all of them by ', it should work normally.
In your original JSON file there are probably going to be some occurrences of \\'. As a string they become \'.
If you’re using Linux, a simple
sed -i "s/\\\\\\\'/\'/g" yourJSONFile.json
on your file fixes everything.
JSONLint says “Valid JSON” then.
You can also try
JSON.parse(json.replace(/\\'/,'\''));

Related

Javascript - Unable to read json key values - Unexpected token i in JSON at position 1 - sql query output problem

I'ved got this string generated from sql query (basically using ARRAY_AGG and some cases to format the output) that looks like this
{id:2,name_of_division:'super department1',attendance_radius:1000}
However, in javascript, I cant get any of the key values and its also causing JSON parse error.
I'ved tried validating this JSON and it looks perfectly fine.
Here are some of the troubleshooting, I have no idea what is causing it
console.log(clean_div_array_var[i].toString());
output ==> {id:2,name_of_division:'super department1',attendance_radius:1000}
console.log("id:" + clean_div_array_var[i].id);
output ==> id:undefined
console.log("name_of_division:" + clean_div_array_var[i].name_of_division);
output ==> name_of_division:undefined
JSON.parse(clean_div_array_var[i]);
output ==>
VM2561:1 Uncaught SyntaxError: Unexpected token i in JSON at position 1
at JSON.parse (<anonymous>)
at get_all_key_of_div_array ((index):817)
at render ((index):2321)
at jquery.dataTables.min.js:18
at Object.b.fnGetData (jquery.dataTables.min.js:12)
at B (jquery.dataTables.min.js:17)
at Ha (jquery.dataTables.min.js:25)
at O (jquery.dataTables.min.js:16)
at jquery.dataTables.min.js:49
at i (jquery.dataTables.min.js:35)
I even try to stringify, then somehow remove quotes (I dont understand why this even appears) and then JSON parse. Same problem.
stringifyvar = JSON.stringify(clean_div_array_var[i])
output ==> "{id:2,name_of_division:'super department1',attendance_radius:1000}"
stringifyvar = stringifyvar.split('\"').join('');
console.log("stringify remove quote:" + stringifyvar);
output ==> stringify remove quote:{id:2,name_of_division:'super department1',attendance_radius:1000}
parsed_json_data = JSON.parse(stringifyvar);
output ==>
VM2503:1 Uncaught SyntaxError: Unexpected token i in JSON at position 1
at JSON.parse (<anonymous>)
at get_all_key_of_div_array ((index):816)
at render ((index):2320)
at jquery.dataTables.min.js:18
at Object.b.fnGetData (jquery.dataTables.min.js:12)
at B (jquery.dataTables.min.js:17)
at Ha (jquery.dataTables.min.js:25)
at O (jquery.dataTables.min.js:16)
at jquery.dataTables.min.js:49
at i (jquery.dataTables.min.js:35)
How can I read any of the keys properly from this json
Your result is not valid JSON. Valid format would be:
{"id":2, "name_of_division":"super department1", "attendance_radius":1000}
The keys have to be quoted, and the quotes around the string super department1 have to be double quotes, not singlequotes.
You need to generate proper JSON if you want to be able to use JSON.parse() to process it.

Error parsing JSON data - "Uncaught SyntaxError: Unexpected token ."

I'm getting the error below in Chrome while parsing a JSON data. The data sample is at http://jsoneditoronline.org/?id=31ffc7c0e7e1a9a2adf641306497b57a This is a valid JSON and my server is sending the correct Content-Type value (application/json).
Uncaught SyntaxError: Unexpected token .
Firefox reports a slightly different message but it all points to the presence of the period (.) in the beginning of the content.
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 6 of the JSON data
I've tried both $.parseJSON() and JSON.parse() methods.
What's the cause of this error? Please enlighten.
I've read the other similar posts here, but they refer to a different character like <, etc.,
EDIT: This is the piece of code I'm using to retrieve the server data.
$.ajax({
url : searchUrl
}).done(function(data) {
var json_array = JSON.parse(data); // Apparently data is already JSON parsed.
});
That data probably is already an object, try it without $.parseJSON() or JSON.parse() and it should work.

JSON: Error while Parsing

I've the following JSON(Valid) sting.
[["abc","{\"icon\":\"adjust\",\"prefix\":\"fa\",\"markerColor\":\"red\"}"],["xyz","{\"icon\":\"archive\",\"prefix\":\"fa\",\"markerColor\":\"green\"}"],["azs","{\"icon\":\"asterisk\",\"prefix\":\"fa\",\"markerColor\":\"darkred\"}"]]
it gives error when I try to Parse using the JSON.parse function
here is the code that I'm using for parsing.
JSON.parse('[["abc","{\"icon\":\"adjust\",\"prefix\":\"fa\",\"markerColor\":\"red\"}"],["xyz","{\"icon\":\"archive\",\"prefix\":\"fa\",\"markerColor\":\"green\"}"],["azs","{\"icon\":\"asterisk\",\"prefix\":\"fa\",\"markerColor\":\"darkred\"}"]]');
and it gives an error in console Uncaught SyntaxError: Unexpected token i
here is the Correct Output by same string using online JSON viewer.
When you use JSON viewer, it's different from when you use the code in your JS code. Like #Jonathan stated, you should double escape you json sting.
JSON.parse('[["abc","{\\"icon\\":\\"adjust\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"red\\"}"],["xyz","{\\"icon\\":\\"archive\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"green\\"}"],["azs","{\\"icon\\":\\"asterisk\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"darkred\\"}"]]');
Your json structure is invalid. You should use this instead(without slashes):
'[["abc",["icon":"adjust","prefix":"fa","markerColor":"red"]],["xyz",["icon":"archive","prefix":"fa","markerColor":"green"]],["azs",["icon":"asterisk","prefix":"fa","markerColor":"darkred"]]'

Three.js SceneExporter getting Uncaught Syntax error

So I am trying to export a three.js scene using the SceneExporter, I am just doing this
var output = new THREE.SceneExporter().parse(scope.renderingEngine.scene);
When doing this, I get an error
Uncaught SyntaxError: Unexpected token u
Which occurs at line 750 of SceneExporter.js (which is the line where the JSON gets parsed; new THREE.SceneExporter().parse(scope.renderingEngine.scene);)
I don't have anything fancy going on in the scene, just a bunch of geometries. I even tried a scene with no textures in it and still got this error.
Now, if I change that line to simply return the output then JSON.stringify(output) and save this file, the file's JSON does not validate. I get the following error
Parse error on line 1:
"{ \n\t\"metadat
^
Expecting '{', '['
And here is line 1-10 of the JSON file
"{
\n\t\"metadata\": {
\n\t\t\"formatVersion\": 3.2,
\n\t\t\"type\"\t\t: \"scene\",
\n\t\t\"generatedBy\"\t: \"SceneExporter\",
\n\t\t\"objects\": 153,
\n\t\t\"geometries\": 144,
\n\t\t\"materials\": 5,
\n\t\t\"textures\": 1\n\t
},
\n\n\t\"urlBaseType\": \"relativeToScene\",
Anyone else having this issue?
The syntax error is a "Unexpected token: ILLEGAL" character, probably thrown by your use of "\n\t\t" and others (escape sequences) outside strings. I don't know what you are trying to achieve with escape sequences outside strings, and I don't even know if special characters should be used in JSON.
Also, I see "\" at some of your strings. You can't use "\". You can, however, use "\", that is escape sequence for a "\". Using a single "\" inside a string will give you the "Unexpected token: ILLEGAL" error. "\" must always be followed by a character that makes a valid escape sequence.

read a json string which has a "'" (malformed?)

I need to consume a service which is returning JSON. I have no influence whatsoever on that service (third party).
If I do
JSON.parse (data)
I get an
SyntaxError: Unexpected token
I know the service works because the error occurs depending on input parameters.
In other words, sometimes it definitely works! The HTTP response code is 200 so it is not some kind of access error, and it is repeatable.
Can I assume they are returning malformed JSON?
Writing the data as a text file to disk and reading it like this:
fs = require('fs')
fs.readFile 'output.json', '', (err, data) ->
if err?
console.log err
json = JSON.parse(data)
console.log json
returns
undefined:1
De L\'Embustier
^
SyntaxError: Unexpected token '
at Object.parse (native)
which is kind of strange because it seems as if the string is correctly escaped but it's nevertheless not being read correctly.
The file is 300+k; haven't seen how to attach it.
EDIT:
Response from jsonlint.com
Parse error on line 1297:
... "Address": "36 Rue De L\'Embust
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
EDIT2:
Here is the whole file then:
http://pastebin.com/ACUfvPCx
The service is indeed returning malformed JSON.
There is no \' escape sequence in JSON. It's perfectly valid to escape any character in Javascript, but JSON uses a subset of the Javascript syntax and only allows escaping characters that actually could need escaping. As an apostrophe is not used as a string delimiter in JSON, it never needs escaping.
If you can't get the service fixed, you would need to request the JSON as plain text, replace the escaped apostrophes with just the apostrophe itself, then parse the text as JSON.

Categories

Resources