matt
matt

Reputation: 44413

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!

Upvotes: 0

Views: 1346

Answers (4)

user1106925
user1106925

Reputation:

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

Upvotes: 1

sngregory
sngregory

Reputation: 406

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

info.application.proId = id;

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150080

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

Upvotes: 0

Dennis
Dennis

Reputation: 32608

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.

Upvotes: 1

Related Questions