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"}';
Related
I am trying to use JQuery to parse some JSON being sent back from an AJAX call. It appears to be failing to parse, and JSLint also says it's invalid JSON.
However, if I create the object directly, it works and I am able to loop through it - please see below:
var json = {layers:[{layer1:[17,16,15,14,12]}]}
alert(json)// <- This works and output object Object
var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"
var parsing = JSON.parse(somestring)
alert(parsing) // <- this doesn't and breaks on parse
// The below code will work provided the parsing is commented out
json.layers.forEach(function (outerObj)
{
Object.keys(outerObj).forEach(function (key)
{
outerObj[key].forEach(function (item)
{
alert(item)
});
});
});
I'm struggling to wrap my head around why it won't parse, but appears to work.
Edit
I realise by wrapping quotes around layers and layer1 fixes it, just not sure why it works one way - but not the other.
there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.
var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.
so the correct JSON string will look like
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
var parsedJson = JSON.parse(somestring)
If you change sometring to some of the following examples, it will works.
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'
var somestring = "{\"layers\":[{\"layer1\":[17,16,15,14,12]}]}"
The reason for this is, basically, that's how JSON was specified.
For further examples, take a look at w3schools
Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.
In your example, you could resolve the problem by
var somestring = JSON.stringify(json)
For future reference, however, JSON keys must be quoted, so your somestring should be written as:
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'
Good luck!
This follows on from my question earlier about Visual Studio showing "" instead of ".
When I run the code below it creates a javascript array and returned as res[0] like below:
["Name","Name","Name"]
in visual studio it returns this:
"["Name","Name","Name"]"
When I run the code, this part shows the surrounding speech marks still (autocompletedata):
autocomplete(document.getElementById("rd-search-form-input"), autocompletedata );
This causes the code to not work. When i manually remove the surrounding double quotes, all works fine.
I've tried removing the start and end part of the string but it just removes the [ and ], which indicates that the string isn't surrounded by double quotes at all. I've also tried removing all double quotes but to no avail.
Can anyone explain whats going wrong?
var urlMethod = "/ajax.aspx/GetTeamMemberNamesList";
var params = new Object();
var result;
params.TeamID = 123;
result = SendAjaxSingleValue(urlMethod, params);
var res = result.d.split("|");
var autocompletedata = res[0];
autocompletedata.replace(/['"]+/g, '')
autocomplete(document.getElementById("rd-search-form-input"), autocompletedata );
To clarify the solution from the OP, the ajax call returns not the array itself but a JSON string, as is always the case when receiving data from a web server - hence why res[0] is returned as ["Name","Name","Name"].
Hence, in order to turn the response text into an actual array, it requires JSON.parse to perform the conversion.
Well, this was annoying - this fixed my issue:
autocomplete(document.getElementById("rd-search-form-input"), JSON.parse(autocompletedata));
When I send an object with an array of objects in it from my express route to my client, I get an [Object object] and then when I try to stringify it, I get this crazy string with this console message
var messages = "<%=(JSON.stringify(messages))%>"
console.log(messages)
Which prints this out to the console ...
{"messages":[{"content":"cool mane","creator":"joe"},{"content":"test 4","creator":"joe"},{"content":" ewgdqf","creator":"joe"},
It should be something so I can iterate through it by doing
messages[0].content but I'm getting this crazy string that won't let me do anything with it...
If I try to loop through it, it just prints out each character by itself.
When using <%= ... %>, EJS will encode / escape any output. That's why the " in the JSON are encoded as ". According to this answer, you can prevent escaping by using <%- ... %> instead.
There is also no need to put the output inside a string literal. It's actually bad since you can get problems with nested quotes. Just let it output directly into the JS code:
var messages = <%-JSON.stringify(messages)%>;
Try to change this :
var messages = "<%=(JSON.stringify(messages))%>"
console.log(messages)
With this :
var messages = JSON.stringify("<%=messages%>");
console.log(messages)
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.
I want to pass Objects as parameters to the javascript function and
I had tried with the following,Actually iam calling the function the function in innerHtml..
var tempObj={
result:results,
jsobj:jsObj
}
str +='<input type="button" onclick="buildCstrWiseChart('+tempObj+')" value="View" class="btn btn-info">';
but this didnt works for me iam getting the error like..
SyntaxError: missing ] after element list
[Break On This Error]
buildCstrWiseChart([object Object])
can any one help in this..
You were treating an object as if it were a string. That's the error.
Is tempObj a global variable? If so, just do
str +='<input type="button" onclick="buildCstrWiseChart(tempObj)" value="View" class="btn btn-info">';`
The string representation of an object is just [object Object] so when you attempt to concatenate it when building your HTML you end up with
onclick="buildCstrWiseChart([object Object])"
which isn't valid HTML. The [object part is parsed as the start of an array, but the Object] part isn't valid array syntax.
I'd suggest, rather than building a HTML string, you instead use jQuery to actually create the DOM element:
$('<input type="button"/>', {
value: 'View',
className: 'btn btn-info'
}).click(function() {
buildCstrWiseChart(tempObj);
});
Then use either the .append() or .appendTo() jQuery function to add that element to whatever containing element you want it to be inside of.
NB: OP has changed the code posted since originally posting.
I'd wager the issue is with this:
...onclick="buildCstrWiseChart('+tempObj+')"...
I don't think that'd work when tempObj isn't something other than a string. Seems dangerous to do in any case.
What you'd really need to do is instead of putting the actual object in the string, put in a value that references it (perhaps build a dictionary of id:object) and just include the id as a data-attribute. Then in your onclick method you can look up that attribute, and find the object for the supplied ID.
Well, the problem is in your function someFunc.
The following example works perfectly fine:
var f = function (el){
alert(el)
};
var x = {a: "hey", b: "ho"};
Then
f('hi');
f(x);
gives no errors.