How to JSON decode array elements in JavaScript? - javascript

I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be.
But if I try to do a redirect or simply do an 'alert' on the link array element I get:
function(){return JSON.encode(this);}
As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck.
After following some suggestions I've run eval('(' + jsonObject + ')') but it still returns the same output.
So how's this done ?

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
See the jQuery API.

Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -
echo json_encode($iniData);
In Javascript, use the following :
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "ajaxCalls.php",
data: "dataType=ini",
success: function(msg)
{
var x = eval('(' + msg + ')');
$('#allowed').html(x.allowed); // these are the fields which you can now easily access..
$('#completed').html(x.completed);
$('#running').html(x.running);
$('#expired').html(x.expired);
$('#balance').html(x.balance);
}
});
});
</script>

If you get this text in an alert:
function(){return JSON.encode(this);}
when you try alert(myArray[i]), then there are a few possibilities:
myArray[i] is a function (most likely)
myArray[i] is the literal string "function(){return JSON.encode(this);}"
myArray[i] has a .toString() method that returns that function or that string. This is the least likely of the three.
The simplest way to tell would be to check typeof(myArray[i]).

eval('(' + jsonObject + ')')

JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.
You will then have a JavaScript datastructure that you can traverse for the data you need.

If the object element you get is a function, you can try this:
var url = myArray[i]();

I decode JSON this way:
eval( 'var from_json_object = ' + my_json_str + ';' );

Related

Use String as object in javascript?

Here I am dynamically getting a string like this:
var datN="{y:12 ,marker: {symbol: 'url(http://abc.com//1446/t_23718.gif)'}},72.72727,83.333336";
I want to use it in HighChart api as graph data but this is not working. I have tried and got this that if the code was like this it would work:
var datN=[{y:12 ,marker: {symbol: 'url(http://abc.com//1446/t_23718.gif)'}},72.72727,83.333336];
so how can I convert the first variable to work like the second one? I am new to javascript please help?
UPDATE
All I want is to convert the first string to object like second one (Second one is working correctly) . I have already tries JSON.parse and eval but they didnt work. So please help?
var datArr = JSON.parse("[" + datN + "]");
This may not work across browsers because JSON.parse is not supported by all browsers. I think you could use jquery
var datArr = $.parseJSON("[" + datN + "]");
If it still does not work, you may try
var datArr = eval("[" + datN + "]");
Although this solution is not recommended.

JSON object to Javascript object

Im looking for a simple script to convert JSON objects to Javascript objects, specifically being able to make an ajax call in jQuery and then convert all of the JSON that comes back into Javascript objects for me.
I've used the mapping plugin in KnockOut.js: https://github.com/SteveSanderson/knockout.mapping/tree/master/build/output
Which nicely takes my JSON result and creates the relevant objects in knockout.
Anything currently exist to do this without knockout?
jquery automatically does this for you.
from the JQuery documentation for getJSON:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
Just specify the dataType setting as 'json' in the $.ajax call, or use the $.getJSON method, and the JSON result will automatically be parsed into a Javascript object.
I'm guessing here, but if you want to convert them into already defined javascript objects you need the second argument in the JSON.parse function. Check MDN's documentation https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse.
Very simple example.
JSON.parse(json,function(prop,val){
if(prop==='objName'){
new myObj(val);
}
});
For use in JQUERY: http://api.jquery.com/jQuery.parseJSON/
For use in simple JS: https://github.com/douglascrockford/JSON-js (look at json.js or json2.js)
Knowing that it's well-formed:
var myObject = eval('(' + myJSONtext + ')');

Changing Attributes of json object in Android application (Titanium)

Hi I am developing Android application using Titanium.I want to change value of particular attributes of json object.I tried following code :
var row_jsonfeed = this.responseText;
var jsonfeed = eval('('+row_jsonfeed+')');
my jsonfeed object look like this :
{"feeds":
[
{"username":"abc","user":"abc","feed":{"description":"dss","id":660,"user_id":1}},
{"username":"bcd","user":"bcd","feed":{"description":"dddd","id":659,"user_id":1}}
]
}
I want to change username value so I tried like this:
jsonfeed.feeds[0].username = "xyz";
alert(jsonfeed.feeds[0].username);
But it's not working.It not giving me changed value of username.Any other alternative way to do this. Instead of eval I also tried JSON.parse but that also not working.So i need proper way to do this.Thank you in advance.
I think the problem is with your call to eval. You forgot to concatenate your parens:
eval('(' + row_jsonfeed + ')');

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