简体   繁体   中英

jQuery/Javascript: insert ID into jSON object?

I get the following object as a paramter via a function call from a flashMovie. So I have a simple javascript function like savePro(info) that is called from a flashmovie.

So I can simply console.log(info) and I get this.

{"action":"setProjectAll", "application":{"proId":"new","zoomPosition":35,"scrollerPosition":0,"language":"en","timelinePosition":0}, "clips":[]}

I have a variable var id = 12 inside my js file. This variable is dynamic but it always holds a number.

How can I replace the "proID":"new" inside the json object with the id of my variable? So I want to have …

{"action":"setProjectAll", "application":{"proId":12,"zoomPosition":35,"scrollerPosition":0,"language":"en","timelinePosition":0}, "clips":[]}

afterwards.

I have absolutely no idea how to do so? Thank you in advance!

Use dot notation to access the property:

info.application.proId = id;

Side note: JSON is a string representation used for interchange. What it looks like you are dealing with is just a JavaScript object .

Well, if this is actual JSON text you're talking about, you'd either need to

  • attempt some fancy string manipulation, or
  • parse it, modify it, then stringify it

The latter would be like this...

var obj = JSON.parse(info);  // parse the JSON into a JavaScript object

obj.application.proId = id; // modify the object

info = JSON.stringify(obj);  // stringify it into JSON if you wanted it as JSON

If you really do not have JSON data, then you'd just manipulate it in the manner that you'd find in any beginner JavaScript book.

That would be the same approach as the second line of code above...

info.application.proId = id; // modify the object

You don't have a "json object", you either have "json", which is a string representation of your object, or you have an "object". Assuming the latter you can set the property as follows:

info.application.proId = id;

If you have JSON you need to parse it to create an object and then set the property (and if you need it as a string turn it back to JSON afterwards):

info = JSON.parse(info);
info.application.proId = id;
info = JSON.stringify(info);

You can access properties in a JSON object using dot notation. Like this:

info.application.proId = id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM