Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse to array

Tags:

json

jquery

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

like image 702
John Avatar asked Feb 28 '12 15:02

John


4 Answers

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

like image 129
Selvakumar Arumugam Avatar answered Oct 23 '22 21:10

Selvakumar Arumugam


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()

like image 44
udidu Avatar answered Oct 23 '22 19:10

udidu


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>
like image 38
Umesh Patil Avatar answered Oct 23 '22 20:10

Umesh Patil


var deniedTimeIDs = $.parseJSON('[808,809,812,811,814,815]');
like image 21
Diode Avatar answered Oct 23 '22 21:10

Diode