大家好
我有一些 JSON 代码,如下所示:
{ playlist: [
'URL goes here',
{
// our song
url: 'another URL goes here'
}
]
}
我想将 javascript 变量的值粘贴到 JSON 中,并用它代替“URL goes here”。有没有办法在 JSON 中做到这一点?我是 JSON 的新手,因此非常感谢您的帮助。要替换的变量的值将来自 getElementById().getAttribute() 之类的东西。
谢谢, 北K
最佳答案
所以我假设您有一个名为 jsonObject
的 json 对象:
var url = "http://example.com/";
jsonObject.playlist[0] = url;
另一方面,如果您正在谈论构建 json 对象,那么您只需将变量放在正确的位置:
var url = "http://example.com/";
var jsonObject = {playlist: [
url,
{
// our song
url: 'another URL goes here'
}
]
}
请注意,url
在我们的列表中用作变量没有问题,同时也用作紧随其后的对象中的键。
关于json 的 Javascript 变量替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1885480/