Proper use of eval in javascript? - javascript

So I have this json object where the structure is variable depending on how you retrieve the data. Lets say the object looks like this in one case:
{
"status": "success",
"data": {
"users": [...]
}
}
but looks like this in another case:
{
"status": "success",
"data": {
"posts": [...]
}
}
Now for the first example, they way I am dynamically getting the data is like this:
var dataLocation = 'data.users';
var responseData;
eval('responseData = response.' +dataLocation + ';');
This allow me to configuration it. Just note that this is just a simple example, in the real code there is only one function to parse the data and I would be passed dataLocation in as a parameter.
Now my first question is whether or not there is a better want to accomplish the same goal without using eval?
If not, the second question is what do I need to do to the eval statement to make sure it is safe (dataLocation should never be passed in from a user, it will always come from code but still).
UPDATE
Based on the comment from Bergi, I am now using this:
var parts = dataListLocation.split('.');
for(var x = 0; x < parts.length; x += 1) {
responseData = responseData[parts[x]];
}

You should use bracket notation instead of eval:
var responseData = response['data']['users'];
Note: from your description, what you have is a JavaScript object literal. A JSON would be that same object encoded as a string (with JSON.stringify, for example). There is no such thing as a "JSON object", you either have a JavaScript object, or a JSON string.

You can use key indexers for objects in JS:
var responseData response.data['users]';
That is after getting rid of the data. in our dataLocation

Related

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: How to convert JSON dot string into object reference

I have a string: items[0].name that I want to apply to a JSON object: {"items":[{"name":"test"}]} which is contained in the variable test. I want to apply that string to the object in order to search it (test.items[0].name). I can only think of one way to do this: parse the square brackets and dots using my own function. Is there another way I can do this? Perhaps using eval? (Even though I'd LOVE to avoid that...)
For clarity:
I have a JSON object, what is inside of it is really irrelevant. I need to be able to query the object like so: theobject.items[0], this is normal behaviour of a JSON object obviously. The issue is, that query string (ie. items[0]) is unknown - call it user input if you like - it is literally a string (var thisIsAString = "items[0]"). So, I need a way to append that query string to theobject in order for it to return the value at theobject.items[0]
function locate(obj, path) {
path = path.split('.');
var arrayPattern = /(.+)\[(\d+)\]/;
for (var i = 0; i < path.length; i++) {
var match = arrayPattern.exec(path[i]);
if (match) {
obj = obj[match[1]][parseInt(match[2])];
} else {
obj = obj[path[i]];
}
}
return obj;
}
var name = locate(test, 'items[0].name');
...JSON doesn't have objects, it's just a string.
If you're dealing with an object (ie: you can reference it using dot/bracket notation) then it's just a JavaScript object/array...
So depending on what the deal is, if you're dealing with a 100% string:
'{"name":"string","array":[0,1,2]}'
Then you need to send it through JSON.parse;
var json_string = '{"name":"string","array":[0,1,2]}',
js_obj = JSON.parse(json_string);
js_obj.name; // "string"
js_obj.array; // [0,1,2]
js_obj.array[1]; // 1
If it's not a string, and is indeed an object/array, with other objects/arrays inside, then you just need to go:
myObj.items[0].name = items[0].name;
If it IS a string, then .parse it, and use the parsed object to do exactly what I just did.
If it needs to be a string again, to send to the server, then use JSON.stringify like:
var json_string = JSON.stringify(js_obj);
Now you've got your modified JSON string back.
If you need to support GhettoIE (IE < 8), then download json2.js from Douglas Crockford, and add that script on the page conditionally, if you can't find window.JSON.

How to use the json?

I have called an api using href from the html form and it in response gives json as output.
consider this as the json the api gives
{
"entry":
{
"id": "1",
"name": "SA"
}
}
I want the values of the id and name.
How can i get the values specifically and store those values to a variable.
Also i got to do this in the html form with javascript.
I want the values of the city_id and city_name. How can i get the
values specifically and store those values to a variable
Use JSON.parse to convert it to JS object and get your values:
var obj = JSON.parse(yourJSON);
var city_id = obj['entry']['city_id'];
var city_name = obj['entry']['city_name'];
Docs:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse
var a;
eval('a={"entry":{"#collection_url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f4602e2c000016","#created_at": "2012-06-21T09:12:40Z","#trash": false,"#type": "City","#updated_at": "2012-06-21T09:12:40Z","#url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f460e2c000016/entries/4fe2e58898f4604757000006","#version": 1,"city_id": "City_001","city_name": "London"}}');
in other words
eval ('a={/*response object*/}')
now you have (a) as object that contains your data you can access them whether like object notation (a.entry) or as an array (a['entry'])
you can also use json parse but its not compatible with all browsers
Either the eval() function or the JSON parser will allow you to create an object from the JSON and then access the fields normally. The JSON parser is a little more secure, as explained in this tutorial:
http://www.w3schools.com/json/json_eval.asp

How do I add one single value to a JSON array?

I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!
Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.
Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };
{} is not an array is an object literal, use loadedRecords = []; instead.
If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}
Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}
Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];

New to JSON, what can I do with this json response

A website returns the following JSON response, how would I consume it (in javascript)?
[{"ID1":9996,"ID2":22}]
Is JSON simply returning an array?
We use:
function evalResponse(response) {
var xyz123 = null;
eval("xyz123 = " + response);
return xyz123;
}
An alternative method is to simply use:
var myObj = eval(response);
Basically, you have to call eval() on the response to create a javascript object. This is because the response itself is just a string when you get it back from your AJAX call. After you eval it, you have an object that you can manipulate.
function myCallback(response) {
var myObj = evalResponse(response);
alert(myObj.ID1);
}
You could use a javascript library to handle this for you. Or, you could try to parse the string yourself. eval() has it's own problems, but it works.
If you use http://www.JSON.org/json2.js you can use it's method JSON.parse to retrieve the json string as an object (without the use of eval (which is considered evil)), so in this case you would use:
var nwObj = JSON.parse('[{"ID1":9996,"ID2":22}]');
alert(nwObj.ID1); //=> 9996
It looks like an array with a single object holding two properties. I'd much prefer to see the same data structured like this:
{"ID":[9996,22]}
Then you have a single object holding an array with two elements, which seems to be a better fit for the data presented. Then using Endangered's evalResponse() code you could use it like this:
var responseObj = evalResponse(response);
// responseObj.ID[0] would be 9996, responseObj.ID[1] would be 22
I think the other answers might not answer your question, maybe you're looking for a way to use that "array of 1 object". Maybe this can help:
var arr = [{"ID1":9996,"ID2":22}];
var obj = arr[0];
var id1 = obj.ID1;
var id2 = obj.ID2;
Here's how you get to your data:
<script type="text/javascript" >
var something = [{"ID1":9996,"ID2":22}]
alert(something[0].ID1)
</script>
The JSON you posted represents an array containing one object, which has attributes ID1 and ID2 (initialized to the respective values after the colon).
To convert the string to a javascript object, pass it to eval, like this:
var obj = eval('[{"ID1":9996,"ID2":22}]');
However, this method will fail if you only have a single object instead of an array, so it is safer to wrap it in parenthesis:
var obj = eval('(' + jsonResponse + ')');

Categories

Resources