7

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

6
  • 3
    Please show your JSON data, not your server code. We can't guess what it looks like. Commented Feb 28, 2012 at 15:17
  • What exactly are you trying to parse? JSON.parse parses a String representation of json object and converts into an actual json object. What you have passed, is not a json String. Commented Feb 28, 2012 at 15:19
  • 1
    Your code actually works for me. jsfiddle.net/Q7Sp5 Commented Feb 28, 2012 at 15:22
  • Then your deniedTimeIDs already holds a valid array after executing the above. You can consume it readily thereafter. Commented Feb 28, 2012 at 15:23
  • how to add / delete data to this? Commented Feb 28, 2012 at 15:23

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

4

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>

Comments

4

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.