North Krimsly
North Krimsly

Reputation: 889

Javascript variable substitution for json

Greetings all,

I have some JSON code that looks like this:

{ playlist: [ 
    'URL goes here', 
    { 
        // our song 
        url: 'another URL goes here'
    }
  ]  
}

I'd like to stick the value of a javascript variable into the JSON, and have it be substituted in place of 'URL goes here'. Is there a way to do that in JSON? I'm a noob at JSON so help would be much appreciated. The value of the variable to substitute would come from something like getElementById().getAttribute().

Thanks, NorthK

Upvotes: 3

Views: 10029

Answers (3)

Chetan
Chetan

Reputation: 5095

use [ ] i.e square brackets to represent a variable

e.g [temp], where temp is a variable

Upvotes: 0

Eli Courtwright
Eli Courtwright

Reputation: 193131

So I'm assuming that you have a json object called jsonObject:

var url = "http://example.com/";
jsonObject.playlist[0] = url;

On the other hand, if you're talking about construction the json object, then you just put the variable into the right position:

var url = "http://example.com/";
var jsonObject = {playlist: [ 
    url, 
    { 
        // our song 
        url: 'another URL goes here'
    }
  ]  
}

Note that there's no problem with url being used as a variable in our list, while also being used as a key in the object that comes right after it.

Upvotes: 9

nickf
nickf

Reputation: 546333

Remember that JSON stands for Javascript Object Notation. It's just a way to encode objects into a string so you can pass it about easily (eg: over HTTP). In your code, it should have already been parsed into an object, therefore you can modify it like any other object: it's nothing special.

var newURL = = document.getElementById('foo').href; // or whatever...
myObject.playlist[0] = newURL;

Upvotes: 1

Related Questions