【问题标题】:Referencing a JSON key with Javascript variable [duplicate]使用 Javascript 变量引用 JSON 密钥 [重复]
【发布时间】:2015-02-22 20:23:21
【问题描述】:

如何将“Argentina”键替换为 javascript 变量字符串?

jQuery(document).ready(function() {

    $.getJSON('countries.json', function(data) {

        var output= data.Argentina[0].countryPhone1;

        alert(output);

     });
});

这是我的 .json 数据文件的样子:

{
    "Argentina": [{
        "countryName":"Argentina",
        "countryPhone1":"1234"
    }],

    "Brazil": [{
        "countryName":"Brazil",
        "countryPhone1":"5678"
    }]
}

我尝试应用建议的解决方案 hereherehere,但我想不出办法让它们适应我的示例。

【问题讨论】:

    标签: javascript json


    【解决方案1】:
    var myString = 'Argentina';  /* or whatever you like */
    
    var output = data[myString][0].countryPhone1;
    

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 2023-04-02
      • 2014-11-29
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      相关资源
      最近更新 更多