获取JSON对象的值

时间:2017-04-28 07:11:10

标签: jquery json

我有低于JSON的输出,并希望根据输入获得特定值

"quotes": {
  "USDAUD": 1.278342,
  "USDEUR": 0.908019,
  "USDGBP": 0.645558,
  "USDPLN": 3.731504
}

现在我有用户输入的美元和英镑

我怎样才能从"引号",

中获取特定值

我试过如下,

from = $("#from option:selected").val();  //this is USD
to = $("#to option:selected").val();  //this is GBP

然后我通过

创建了一个字符串
output = to + from;

并尝试在控制台中获取价值

console.log(json.quotes);  //this gives complete output in console
console.log(json.quotes.output); //but with this i could not get value of USDGBP

如何从JSON对象获取所需的值?

2 个答案:

答案 0 :(得分:1)

在javascript中,对象和数组的用法非常相似。

因此,将创建的对象作为数组进行查找:

output = from + to;
if (quotes[output]!==undefined)
{
    var yourValue=quotes[output];
}

答案 1 :(得分:1)

原因输出是一个字符串,你不能只需json.quotes.output将它放在方括号中,如:

json.quotes[output]



var json = {
  "quotes": {
    "USDAUD": 1.278342,
    "USDEUR": 0.908019,
    "USDGBP": 0.645558,
    "USDPLN": 3.731504
  }
};

var from = 'GBP';
var to = 'USD';
var output = to + from;
console.log(output);

console.log(json.quotes);  //this gives complete output in console
console.log(json.quotes[output]); //but with this i could not get value of USDGBP




相关问题