Convert Json To Array Javascript
I am currently receiving a JSON Object From the Server side of my application, the result is this {'tags':'[{value: 2,label: 'Dubstep'},{value: 3,label: 'BoysIIMen'},{value: 4,labe
Solution 1:
Assuming you got your server side response in a javascript object called response
you could parse the tags
string property using the $.parseJSON
function. But first you will need to fix your server side code so that it returns a valid JSON string for the tags property (in JSON property names must be enclosed in quotes):
// This came from the servervar response = {"tags":"[{\"value\": 2,\"label\": \"Dubstep\"},{\"value\": 3,\"label\": \"BoysIIMen\"},{\"value\": 4,\"label\":\"Sylenth1\"}]"};
// Now you could parse the tags string property into a corresponding// javascript array:var tags = $.parseJSON(response.tags);
// and at this stage the tags object will contain the desired array// and you could access individual elements from it:
alert(tags[0].label);
If for some reason you cannot modify your server side script to provide a valid JSON in the tags
property you could still use eval
instead of $.parseJSON
:
var tags = eval(response.tags);
It's not a recommended approach, normally you should avoid using eval
because it will execute arbitrary javascript.
Solution 2:
initSelection: function (element, callback) {
var data = $(element).val();
callback($.parseJSON(data));
}
Post a Comment for "Convert Json To Array Javascript"