JSON.Parse,'Uncaught SyntaxError: Unexpected token o [duplicate] - javascript

This question already has answers here:
I keep getting "Uncaught SyntaxError: Unexpected token o"
(9 answers)
Closed 6 years ago.
I am having trouble with JSON returned from a web service. It looks like the JSON lacks quotes, but when I add quotes to the JSON, I get an error. Here is the error message: 'Uncaught SyntaxError: Unexpected token o. When I log the string to console:[object Object],[object Object]
Here is some example code that simulates the error:
//Error I am trying to solve
var jsonString = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
var myData = JSON.parse(jsonString);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + '</li>').appendTo($grouplist);
});
});
Here is the same code with the single quotes around the string. It works
//Successful Javascript
var jsonString = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
var myData = JSON.parse(jsonString);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + '</li>').appendTo($grouplist);
});
});
//Successful HTML
<ul id="groups"></ul>
But when I try to add quotes to the string, like I seem to need to in my real code, it fails:
//Does not work when I need to append quotes to the string:
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
jsonStringQuotes = "'" + jsonStringNoQuotes + "'";
var myData = JSON.parse(jsonStringQuotes);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + ',' + this.Id + '</li>').appendTo($grouplist);
});
});
Here is the error:
log string to console:[object Object],[object Object]
data.js:809 Uncaught SyntaxError: Unexpected token '
I'm stumped. Any help appreciated! Thank you!

Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse to convert a string into a JavaScript object. You cannot use JSON.parse to convert a JavaScript object into a JavaScript object.
//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log the following...
console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'
You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.
Why does this happen? Because you are starting with a string "'", then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'".
Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.
See this fiddle:
http://jsfiddle.net/NrnK5/

var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
it will create json object. no need to parse.
jsonStringQuotes = "'" + jsonStringNoQuotes + "'";
will return '[object]'
thats why it(below) is causing error
var myData = JSON.parse(jsonStringQuotes);

Your last example is invalid JSON. Single quotes are not allowed in JSON except inside strings. In the second example, the single quotes are not in the string, but serve to show the start and end.
See http://www.json.org/ for the specifications.
Should add: Why do you think this: "like I seem to need to in my real code"? Then maybe we can help you come up with the solution.

Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:
$.get('/service', function(data) {
var obj = data;
/*
"obj" is evaluated at this point if server responded
with "application/json" or similar.
*/
for (var i = 0; i < obj.length; i++) {
console.log(obj[i].Name);
}
});
Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify:
var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);
But in this case I don't understand why you can't just take the json variable and refer to it instead of stringifying and parsing.

Related

Generating fully valid JSON with client-side JavaScript

So I am trying to create a JSON explorer / editor. I am able to parse the initial JSON into the div and format it how I like.
this is the function i use to loop through the initial JSON
_iterate(_tab, raw_json){
var tab = _tab;
tab++;
for(var key1 in raw_json){
var data_type = typeof raw_json[key1];
var d = String(raw_json[key1])
if(d == String){
d = "String";
}
if(d == Number){
d= "Number"
}
if(data_type == "object" || data_type == "array"){
this.input.append(`<json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2 -je-${data_type}">'<span class="-je-key">${key1}</span>' :{</div></br>`)
this._iterate(tab, raw_json[key1])
}else{
this.input.append(`<div class="json-editor-row"><json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2">'<span class="-je-key">${key1}<span>' : '<div class="json-editor-input -je-${data_type}" contenteditable="true" for="{key: '${key1}', data: '${d}'}"></div>', </div></br></div>`)
}
}
this.input.append(`<json-tab tab-width="${tab -1}"></json-tab>},</br>`)
}
in order to save the JSON I was going to retrieve the JSON from the text of the div using
getJSON(){
var json_text = this.input.text().slice(0, -1)
return JSON.parse(`"${json_text}"`)
}
right now this is able to be parse by JSON.parse(); but when i want to console.log(getJSON()[0]) this returns {
am i not formating the JSON correctly. a live example of this can be found here
First, your console.log result doesn't make sense. A parsed JSON object is now usable in JavaScript and, if has (only) properties x and y, would result in undefined when requesting property 0 as you have. It looks like your call to console.log was to a different (earlier?) version of the getJSON() function, where it returned the raw string, and in that case it makes sense that you're just retrieving the first character of the JSON text: "{".
But then, assuming the version of getJSON() as written, it would actually throw a parse exception:
VM1511:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Looking at your site, I was able to do, in the console:
jsonString = $('json-editor').text()
// value: "{'partName' : '', 'partRevision' : '', ..."
That is illegal JSON. JSON specifies (only) the quotation mark " for strings (Unicode/ASCII 0x22) on page 7 of its specification.
The fact that 'partName' is legal as a JavaScript string literal is irrelevant but perhaps confusing.
As a minor style point, simplify JSON.parse(`"${json_text}"`) to JSON.parse(json_text).
#BaseZen's answer was very helpful for me to understand what was going wrong with my code. My JSON was incorrectly formatted even though online linters say its correct. Along with what BaseZen pointed out, JSON.parse() will not work with trailing commas. To fix this:
_remove_trailing_commas(json_string){
var regex = /\,(?!\s*?[\{\[\"\'\w])/g;
return json_string.replace(regex, '');
}
I found this information at SO post JSON Remove trailiing comma from last object
SO user Dima Parzhitsky's answer was what helped me also figure out this question.

Replace \" with " in Javascript

I have a JSON from my web server that I obtain from a XMLHttpRequest.
The data has the following form when I print it out using
var data = this.responseText;
console.log("data=" + JSON.stringify(data));
data=[{\"day\":0,\"periods\":[\"0xffffffffffff\"]}]
I process the JSON using jquery but I'm getting an error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"day":0,"periods":["0xffffffffffff"]}]
I'm assuming the problem is due to the escaping of the quotes as if I hard code data to [{"day":0,"periods":["0xffffffffffff"]}]
I don't get the error.
I've tried various ways of getting rid of the escape but without success:
data = data.replace(/\\/g, "");
Does not modify the string at all;
I found a function from another thread, replaceAll, but this:
var newData = data.replaceAll("\\","");
..made no difference either.
Trying to replace \" with ' then replacing the ' with " just returns me to \"
var newData = data.replaceAll("\"","'");
now newData = [{'day':0,'periods':['0xffffffffffff']}]
newData = newData.replaceAll("'","\"");
and it's back to [{\"day\":0,\"periods\":[\"0xffffffffffff\"]}]
Trying to process with single quote, i.e. [{'day':0,'periods':['0xffffffffffff']}] gives me the same Uncaught TypeError message.
Any ideas how I can solve this?
Thanks.
The error is that you are using JSON.stringify on a string. Have an exact look on this.responseText - responseText - that you are using as property. Just change it to
var data = JSON.parse(this.responseText);
console.log("data=" + data);

eval is not working in IE8

I could not find reason why this small code snippet is not working in IE8,
var a = {"ff": "test"};
eval('('+a+')');
I am getting error as
']' expected".
var a = {"ff": "test"};
eval('('+a+')');
This is evaluated as:
([object Object])
And that's obviously not valid JavaScript. If you want to preserve a data structure, you can use JSON.stringify() and JSON.parse().
var a_to_json = JSON.stringify(a);
var a_from_json = JSON.parse(a_to_json);
When concatenating the object a to form part of the eval'd string, a.toString() is called, which will output [object Object]. What you want is for {"ff": "test"}; to be concatenated into the eval'd string, so you'll need to use JSON.stringify() to achieve that.
Try this:
eval('('+JSON.stringify(a)+')');
Or alternatively you could just put quotes around the object declaration on the first line:
var a = '{"ff": "test"}';

How to parse JSON that has inner layers using Javascript?

I can eval simple JSON with javascript.
var json = '{"amount":"50","id":"3"}';
var out = eval("{" + json + "}");
Now I am using JPA with REST and JSON-nized query result would include table name which makes
JSON having inner JSON so simple eval wouldn't work.
{"inventory":{"amount":"50","id":"3"}}
I've looked around the web for solution but can't find my case.
Should I just do string manipulation and extract {"amount":"50","id":"3"} part?
Or is there other way?
Yes, there is another (better) way! Use JSON.parse() to parse your JSON and get your object out:
var obj = JSON.parse(jsonString);
//then, for example...
var amount = obj.inventory.amount;
For older browsers (IE <8 for example) without native JSON support, include json2.js so this above still works.
Even this should work:
var json = '{"inventory":{"amount":"50","id":"3"}}';
var out = eval("{" + json + "}");
alert(out.inventory.amount);
But better to use JSON.parse
Aniway, I think that the proper way to perform a simple eval is to have the json string surrounded with parenthesis, not curly brackets...
var out = eval("(" + json + ")");
Cf. https://github.com/douglascrockford/JSON-js/blob/master/json.js :
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');

How do I convert a JSON string to a function in javascript?

How can I convert a string in javascript/jquery to a function?
I am trying to use a JSON parameter list to initialize a function. However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.
For example, if my JSON is:
json = { "one": 700, "two": "function(e){alert(e);}" }
Then in my code:
parameters = eval(json);
$('myDiv').addThisFeature({
parameter_1: json.one,
parameter_2: eval(json.two) // <= generates error
})
Example: http://jsfiddle.net/patrick_dw/vs83H/
var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
var parameters = JSON.parse( json );
eval( 'var func = ' + parameters.two );
func( 'test' ); // alerts "test"
You'll need to load the JSON library in browsers that don't support it.
Or do two separate evals:
Example: http://jsfiddle.net/patrick_dw/vs83H/1/
var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
eval( 'var parameters = ' + json );
eval( 'var func = ' + parameters.two );
func( 'test' );
I assume you're aware of the dangers of eval.
Looking for a way to not use eval this is the best I could come up with. Use the Function constructor to create a function from a string.
var parsed = JSON.parse('{"one":"700", "two":"function(){return 0;}" }');
var func = new Function('return ' + parsed.two)(); // return parsed.two function
alert(typeof func); // function
alert(func()) // 0
Use this:
parameters = eval('(' + json + ')');
$('#myDiv').addThisFeature({
parameter_1: parameters.one,
parameter_2: eval('(' + parameters.two + ')') // <= does not generate an error
});
Adding the parentheses at the beginning and end of the string prevents the syntax error.
Note, however, that you are parsing JSON using eval (which in some cases has security risks, but I assume that is irrelevant because you do want to run arbitrary code sent by the server). If you have the server-side flexibility (to send invalid JSON), you could just send the function not quoted as a string and eval should be able to parse that just fine.
See this SO question. As was said, JSON is meant to hold data. To treat a piece of the data as a function, you would first need to eval the string.
You are eval'ing an anonymous function, which of course won't be called by anything. If you really wanted to run the code in the json then the text would need to be alert(e).
However it doesn't sound like a very sensible thing to do. You'd be better off writing code to deal with the contents of the json object, rather than trying to run code embedded in the json.
Neither way is particularly nice, but if you can get rid of the function(e) wrapper bits, then you can use var myDynamicFunction = new Function("e", "alert(e);"); Otherwise, you're looking at using eval(). Eval() is evil in general. If this is JSON that you're getting back from a $.getJSON call or something, you're opening yourself up to security concerns.

Categories

Resources