无法从json获取数据进行比较

时间:2014-04-02 15:51:03

标签: javascript jquery json

我创造了一个小提琴here。我基本上试图用json创建a similar demo app来学习jquery 我陷入了“如何通过从localStorage读取数据来计算货币价值? 谁能告诉我实现这一目标的步骤?“

例如。如果我输入USD值为1然后在另一个文本框中输入相应的货币金额

我通过拨打下面的远程网站获得Jason数据

{
    "list": {
        "meta": {
            "type": "resource-list",
            "start": 0,
            "count": 168
        },
        "resources": [{
                "resource": {
                    "classname": "Quote",
                    "fields": {
                        "name": "USD/KRW",
                        "price": "1062.280029",
                        "symbol": "KRW=X",
                        "ts": "1396294510",
                        "type": "currency",
                        "utctime": "2014-03-31T19:35:10+0000",
                        "volume": "0"
                    }
                }
            }, {
                "resource": {
                    "classname": "Quote",
                    "fields": {
                        "name": "SILVER 1 OZ 999 NY",
                        "price": "0.050674",
                        "symbol": "XAG=X",
                        "ts": "1396287757",
                        "type": "currency",
                        "utctime": "2014-03-31T17:42:37+0000",
                        "volume": "217"
                    }
                }
            }


        ]
    }
}

来自小提琴的JavaScript

$(document).ready(function(){
    yahoo_getdata(); 
});
    function yahoo_getdata() {   
    var a = new Date();
    var b = "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json&random=" + a.getTime() + "&callback=?";
    $.getJSON(b, function (e) {
        if (e) {
            console.log(e);
            var d = {};
            d.time = a.getTime();
            d.data = e;    
            localStorage.setItem('all_currencies',JSON.stringify(d));
            var jsonStringFromLS = localStorage.getItem('all_currencies');
            console.log(JSON.parse(jsonStringFromLS));
        }
    });

}
/*
* On keyup on any textfield, the respected currencies should be calculated and should display on respective textboxes...
 "add more textbox" feature i will do by myself after learning the above technique
*/
//----when typed in any of these 3 textbox then convert money----------
$( "#amount1" ).keyup(function() {
    var currency1=$( "#currency1" ).val();
    var currency2=$( "#currency2" ).val();
    $("#amount2").val("2.3");   //
    $("#amount3").val("59.34"); 
});

有人能透露我吗?

1 个答案:

答案 0 :(得分:0)

在一个地方,您需要迭代JSON中的资源,找到您所参与的那些资源,并采用您需要进行计算的价格值。

在你的函数yahoo_getdata()中,你有参数e,它包含数据。所以你可以做到以下几点:

var i, l, r, c;
r = e.list.resources;
for (i = 0, l = r.length; i < l; i += 1) {
  c = r[i].resource.fields;
  switch (c.name) {
    case 'USD/KRW':
      // store c.price somewhere so you can later access it for the calculation
      break;
    // more case for other currencies you may need
  }
}