Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,label:'Sylenth1'}]"}

But then I don't really need the "tags" and the double quotes in the result.

So what I want is an array representation of that JSON object

therefore how would I convert this

{"tags":"[{value: 2,label: 'Dubstep'},{value: 3,label: 'BoysIIMen'},{value: 4,label:'Sylenth1'}]"}

to this

[{value: 2,label: 'Dubstep'},{value: 3,label: 'BoysIIMen'},{value: 4,label:'Sylenth1'}]

Here's the loop that creates the array

String k = "["; 
        List<Tag> tg = audioTaggingService.findTagsByName(q);
        for(int i = 0; i<audioTaggingService.findTagsByName(q).size();i++){
            Tag t = tg.get(i);
            if(i == (tg.size() - 1)){
                k+="{value: "+t.getId()+",label:'"+t.getName()+"'}";
            }else{
                k+="{value: "+t.getId()+",label:'"+t.getName()+"'}";
            }
        }
        k+="]";

The result of the code above is this

[{value: 2,label: 'Dubstep'},{value: 3,label: 'BoysIIMen'},{value: 4,label:'Sylenth1'}]
like image 872
user962206 Avatar asked Jan 30 '13 10:01

user962206


1 Answers

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 server
var 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.

like image 80
Darin Dimitrov Avatar answered Nov 15 '22 19:11

Darin Dimitrov