John
John

Reputation: 747

JSON.parse to array

I have a json object:

var deniedTimeIDs = JSON.parse('[808,809,812,811,814,815]');

so, I want to add/remove data from this object by jquery. How to do it? can I convert it to Array? Thanks

Upvotes: 6

Views: 37191

Answers (4)

udidu
udidu

Reputation: 8588

If you want to parse that String and represent it as an Array you can do the following:

// Warning: eval is weird
var arr = eval('[808,809,812,811,814,815]');

or

var arr= JSON.parse('[808,809,812,811,814,815]');

Now arr is a valid JavaScript array.

UPDATE FROM 2021 ADDING AN OFFICIAL DOC ARTICLE WHICH EXPLAINS WHY eval() IS A DANGEROUS FUNCTION TO CALL:

eval()

Upvotes: 3

Umesh Patil
Umesh Patil

Reputation: 10685

Any Array returned after parsing the String, can be processed with jQuery or JavaScript. We generally use Push() and Pop() function to process any array.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
    var deniedTimeIDs = JSON.parse('[808,809,812,811,814,815]');
    // You can use push/Pop to remove the IDs from an array.
    console.log(deniedTimeIDs);// o/p=> [808,809,812,811,814,815]
    //You can iterate this array using jQuery.
    $.each(deniedTimeIDs,function(key,val){
        console.log(val); 
    })
});
</script>

Upvotes: 4

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Below will give you a javascript object,

var deniedTimeIDs = JSON.parse('[808,809,812,811,814,815]');

You can then use .push & .pop to add/remove element into the array.

deniedTimeIDs.push(100); //will result in [808,809,812,811,814,815,100]

Further Readings,

JSON.parse, Array.push, Array.pop

Upvotes: 5

Diode
Diode

Reputation: 25135

var deniedTimeIDs = $.parseJSON('[808,809,812,811,814,815]');

Upvotes: 1

Related Questions