Error when converting eval() to JSON.parse() - javascript

I have a snippet code with eval() as shown below:
var data = "{listUpdated:[],listConflictOrMerge:[]}"; //returned from Ajax
var results = eval("(" + data + ")");
console.log(results)
As you can see, the data is my input value returned from ajax request. When using eval(), it can be parsed to 2 array objects.
And now I don't want to use eval() anymore, so I try using JSON.parse(). However, there is an error.
var data = "{listUpdated:[],listConflictOrMerge:[]}"; //returned from Ajax
var results = JSON.parse(data);
console.log(results)
my purpose is that I don't want to use eval() to parse data anymore.
So, is there any ways can do that?.
I try using JSON, but I got unlucky. Am I wrong somewhere?

The data you're trying to parse isn't valid JSON, so JSON.parse can't parse it.
Keys in JSON objects must be quoted, just like any other string. The form you're using is valid in Javascript, but invalid in JSON.

var data = '{"listUpdated":[],"listConflictOrMerge":[]}';
var results =JSON.parse(data);
console.log(results)

Related

How to convert the json results to array using javascript?

I need to convert the Json response to array using JavaScript .
I have the json response which is :
["simmakkal madurai","goripalayam madurai"].
now I want to change this results to array format .
So, How to I convert the json result to array.
Try this :-
var obj = $.parseJSON('["simmakkal madurai","goripalayam madurai"]');
If you alert(obj[0]), you will get answer as simmakkal madurai
var arr = JSON.parse('["simmakkal madurai","goripalayam madurai"]');
Yeah,
if your response is
var res = '["simmakkal madurai","goripalayam madurai"]';
Then you just need to do
var arr = JSON.parse(res);
Alternativly you could do an eval but evals are never realy recommended, but since you are going from server side to client side (php -> javascript) it wouldnt the the worst thing.
Anyways JSON.parse should work

Javascript: Parse JSON output result

How can i retrieve the values from such JSON response with javascript, I tried normal JSON parsing seem doesn't work
[["102",true,{"username":"someone"}]]
Tried such codes below:
url: "http://somewebsite.com/api.php?v=json&i=[[102]]",
onComplete: function (response) {
var data = response.json[0];
console.log("User: " + data.username); // doesnt work
var str = '[["102",true,{"username":"someone"}]]';
var data = JSON.parse(str);
console.log("User: " + data[0][2].username);
Surround someone with double quotes
Traverse the array-of-array before attempting to acces the username property
If you are using AJAX to obtain the data, #Alex Puchkov's answer says it best.
So the problem with this is that it looks like an array in an array. So to access an element you would do something like this.
console.log(obj[0][0]);
should print 102
Lets say you created the object like so:
var obj = [["102",true,{"username":someone}]];
this is how you would access each element:
obj[0][0] is 102
obj[0][1] is true
and obj[0][2]["username"] is whatever someone is defined as
From other peoples answers it seems like some of the problem you may be having is parsing a JSON string. The standard way to do that is use JSON.parse, keep in mind this is only needed if the data is a string. This is how it should be done.
var obj = JSON.parse(" [ [ "102", true, { "username" : someone } ] ] ")
It depends on where you are getting JSON from:
If you use jQuery
then jQuery will parse JSON itself and send you a JavaScript variable to callback function. Make sure you provide correct dataType in $.ajax call or use helper method like $.getJSON()
If you getting JSON data via plain AJAX
then you can do:
var jsonVar = JSON.parse(xhReq.responseText);

Javascript JSON.parse or directly access

When we can read a property directly from string:
var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde
Why do people use JSON.parse:
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
It is not a string, but Javascript object. String is given below
var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';
to make it object we use JSON.parse
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
In your first example, data is an object, but in your second example, data is a JSON string.
That's a major difference. You could call eval(data) to parse a JSON string, but that's very unsafe.
JSON.parse() expects a string. More specifically, a string with a JSON-encoded piece of data.
If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format.

Reading JSON properties in NodeJS?

I'm having trouble reading properties from JSON within NodeJS.
Feels like an obvious mistake I may be making..
The JSON is from this endpoint;
http://hypem.com/playlist/history/faisdotal/json/1/data.js
My code:
var request = require('request');
request("http://hypem.com/playlist/history/faisdotal/json/1/data.js", function (err, res, json) {
JSON.parse(json);
console.log(json["1"]["artist"]); // undefined
});
~
You need to store the returned value of JSON.parse:
json = JSON.parse(json);
console.log(json["1"]["artist"]);
I think you want:
json = JSON.parse(json);
It won't (and can't) simply update the value of the parameter. The .parse() routine returns the value parsed from the string you pass it.
JavaScript is purely call-by-value, so there's really no way it could possibly work the way your code is written.

Problem parsing JSON

I encounter problems tring to consume a third party web servive in JSON format. The JSON response from the server kinda looks like this:
{
"ID":10079,
"DateTime":new Date(1288384200000),
"TimeZoneID":"W. Europe Standard Time",
"groupID":284,
"groupOrderID":10
}
I use JavaScript with no additional libs to parse the JSON.
//Parse JSON string to JS Object
var messageAsJSObj = JSON.parse(fullResultJSON);
The parsing fails. A JSON validatior tells me, "new Date(1288384200000)" is not valid.
Is there a library which could help me parse the JSON string?
Like others have pointed out, it's invalid JSON. One solution is to use eval() instead of JSON.parse() but that leaves you with a potential security issue instead.
A better approach might be to search for and replace these offending issues, turning the data into valid JSON:
fullResultJSON = fullResultJSON.replace(/new Date\((\d+)\)/g, '$1');
You can even go one step further and "revive" these fields into JavaScript Date objects using the second argument for JSON.parse():
var messageAsJSObj = JSON.parse(fullResultJSON, function (key, value) {
if (key == "DateTime")
return new Date(value);
return value;
});
Here's an example: http://jsfiddle.net/AndyE/vcXnE/
Your example is not valid JSON, since JSON is a data exchange technology. You can turn your example into a Javascript object using eval:
var almostJSON = "{
"ID":10079,
"DateTime":new Date(1288384200000),
"TimeZoneID":"W. Europe Standard Time",
"groupID":284,
"groupOrderID":10,
}";
and then evaling it:
var myObject = eval('(' + almostJSON + ')');
Then, myObject should hold what you're looking for.
Note that functions are not allowed in JSON because that could compromise security.
try var obj = eval('(' + fullResultJSON + ')'); and you'll have the object like Pekka said. Don't forget to use the extra '()' though. And indeed json should have both property and value enclosed in quotes.
Parsing fails because all you can parse in a json object are null, strings, numbers, objects, arrays and boolean values so new Date(1288384200000), cannot be parsed
You have also another problem, last property shouldn't have the trailing comma.

Categories

Resources