Javascript variable substitution for json
-
19-09-2019 - |
Question
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
Solution
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.
OTHER TIPS
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;