Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 984
North Krimsly Avatar asked Mar 12 '26 03:03

North Krimsly


1 Answers

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.

like image 156
Eli Courtwright Avatar answered Mar 14 '26 15:03

Eli Courtwright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!