简体   繁体   English

JSON 的 Javascript 变量替换

[英]Javascript variable substitution for json

Greetings all,问候大家,

I have some JSON code that looks like this:我有一些看起来像这样的 JSON 代码:

{ 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'.我想将一个 javascript 变量的值粘贴到 JSON 中,并用它代替“URL 在此处”。 Is there a way to do that in JSON?有没有办法在 JSON 中做到这一点? I'm a noob at JSON so help would be much appreciated.我是 JSON 的菜鸟,因此非常感谢您的帮助。 The value of the variable to substitute would come from something like getElementById().getAttribute().要替换的变量的值将来自诸如 getElementById().getAttribute() 之类的东西。

Thanks, NorthK谢谢,北K

So I'm assuming that you have a json object called jsonObject :所以我假设你有一个名为jsonObject的 json 对象:

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:另一方面,如果您正在谈论构建 json 对象,那么您只需将变量放在正确的位置:

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.请注意,将url用作我们列表中的变量并同时用作紧随其后的对象中的键是没有问题的。

Remember that JSON stands for Javascript Object Notation.请记住,JSON 代表 Javascript Object Notation。 It's just a way to encode objects into a string so you can pass it about easily (eg: over HTTP).这只是将对象编码为字符串的一种方法,因此您可以轻松地传递它(例如:通过 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;

use [ ] ie square brackets to represent a variable使用 [ ] 即方括号来表示变量

eg [temp], where temp is a variable例如 [temp],其中 temp 是一个变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM