26

i have a json variable like this

var jsondata={"all":"true"}

i want to push another key and value to the jsondata. after that my jsondata have to be like this.

{"all":"true","FDamount":"false","DDamount":"true"}

how to do that??? i tried jsondata.push({"FDamount":"false"}) and jsondata.push("FDamount:false"). both of these method is not working.

thank you

1
  • 1
    You do not seem to use JSON anywhere? Those are just simple object literals (and no arrays, btw) Commented Dec 22, 2012 at 14:14

2 Answers 2

34

Like this

jsondata.FDamount = 'false';
// or
jsondata['FDamount'] = 'false';
Sign up to request clarification or add additional context in comments.

Comments

9

Simply do this :

jsondata['FDamount'] = 'false';
jsondata['DDamount'] = 'true';

Or this :

jsondata.FDamount = 'false';
jsondata.DDamount = 'true';

By the way, you define boolean as string, the correct way should be :

jsondata['FDamount'] = false;
jsondata['DDamount'] = true;

To push a little bit further, you can use jQuery.extend to extend the original var, like this :

jQuery.extend(jsondata, {'FDamount': 'false', 'DDamount': 'true'});
// Now, jsondata will be :
{"all":"true","FDamount":"false","DDamount":"true"}

jQuery.extend is available when using jQuery (of course), but I'm sure you can find similar methods in other libraries/frameworks.

(I'm using single quotes, but double quotes works too)

3 Comments

How can i do that for each element? I need add new key and value for each element.
What do you mean by "each element" ?
"Each element" is each item when parse to an object your Json Data you can see items. I want add an key with value for each item in your Json structure.

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.