Javascript 变量替换 json
大家好,
我有一些如下所示的 JSON 代码:
{ playlist: [
'URL goes here',
{
// our song
url: 'another URL goes here'
}
]
}
我想将 javascript 变量的值粘贴到 JSON 中,并将其替换为“URL 位于此处”。有没有办法在 JSON 中做到这一点?我是 JSON 新手,因此非常感谢您的帮助。要替换的变量的值来自 getElementById().getAttribute() 之类的内容。
谢谢, 北K
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,我假设您有一个名为
jsonObject
的 json 对象:另一方面,如果您正在谈论构造 json 对象,那么您只需将变量放入正确的位置即可:
请注意
url
用作列表中的变量,同时也用作紧随其后的对象中的键,这是没有问题的。So I'm assuming that you have a json object called
jsonObject
:On the other hand, if you're talking about construction the json object, then you just put the variable into the right position:
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.请记住,JSON 代表 Javascript 对象表示法。它只是将对象编码为字符串的一种方法,以便您可以轻松地传递它(例如:通过 HTTP)。在您的代码中,它应该已经被解析为一个对象,因此您可以像任何其他对象一样修改它:它没有什么特别的。
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.
使用 [ ] 即方括号来表示变量
,例如 [temp],其中 temp 是变量
use [ ] i.e square brackets to represent a variable
e.g [temp], where temp is a variable