Nor*_*sly 3 javascript variables json substitution
问候所有,
我有一些看起来像这样的JSON代码:
{ playlist: [
'URL goes here',
{
// our song
url: 'another URL goes here'
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想将javascript变量的值粘贴到JSON中,并将其替换为"URL goes here".有没有办法在JSON中做到这一点?我是JSON的菜鸟,所以非常感谢帮助.要替换的变量的值将来自getElementById().getAttribute().
谢谢,NorthK
所以我假设你有一个名为的json对象jsonObject
:
var url = "http://example.com/";
jsonObject.playlist[0] = url;
Run Code Online (Sandbox Code Playgroud)
另一方面,如果你正在讨论构造json对象,那么你只需将变量放到正确的位置:
var url = "http://example.com/";
var jsonObject = {playlist: [
url,
{
// our song
url: 'another URL goes here'
}
]
}
Run Code Online (Sandbox Code Playgroud)
请注意,url
在列表中用作变量没有问题,同时也用作紧随其后的对象中的键.