【问题标题】:Extracting data from json object in jQuery or JS从 jQuery 或 JS 中的 json 对象中提取数据
【发布时间】:2012-06-07 06:49:39
【问题描述】:

我想使用https://raw.github.com/currencybot/open-exchange-rates/master/latest.json提供的币种数据

作为初始测试,我创建了一个缩减版作为内联对象:

var obj = [
{
    "disclaimer": "This data is collected from various providers and provided free of charge for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability, or fitness for any purpose; use at your own risk. Other than that, have fun! More info: http://openexchangerates.org/terms/",
    "license": "Data collected from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given. Full license info: http://openexchangerates.org/license/",
    "timestamp": 1339036116,
    "base": "USD",
    "rates": {
        "EUR": 0.795767,
        "GBP": 0.645895,
        "JPY": 79.324997,
        "USD": 1
    }
}];

我想要做的就是以某种方式查询/grep/过滤json对象,例如,“EUR”作为条件,并让它返回一个名为“rate”的变量,其值为“0.795767”结果。

我查看了 JQuery grep 和 filter 函数,但不知道如何仅隔离对象的“rates”部分,然后获得我想要的速率。

【问题讨论】:

    标签: javascript jquery json


    【解决方案1】:
    var obj = [
    {
        "disclaimer": "This data is collected from various providers and provided free of charge for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability, or fitness for any purpose; use at your own risk. Other than that, have fun! More info: http://openexchangerates.org/terms/",
        "license": "Data collected from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given. Full license info: http://openexchangerates.org/license/",
        "timestamp": 1339036116,
        "base": "USD",
        "rates": {
            "EUR": 0.795767,
            "GBP": 0.645895,
            "JPY": 79.324997,
            "USD": 1
        }
    }];
    
    obj[0].rates.EUR; // output: 0.795767
    

    obj[0].rates['EUR']; output: //0.795767
    

    DEMO

    如果您想在另一个变量中隔离费率并使用该变量,请尝试以下操作:

    var rates = obj[0].rates;
    

    现在,

    rates.EUR;
    rates.GBP;
    

    等等。

    【讨论】:

    • 太好了,这正是我想要的。我不知道它会这么简单。
    • 我的 json 数据是 {"0":{"level1":"done","level2":"done","level3":"no"}} 如何将其提取到每个变量中?我尝试使用$.each 方法,但返回未定义的var level1 = ele[0].level1;
    【解决方案2】:

    您也可以使用 Javascript 的JSON.parse() 函数将 JSON String 转换为 Javascript JSON 对象。

    var JSONObject = JSON.parse("{'value1' : 1, 'value2' : 2}");
    console.log(JSONObject.value1);  // Prints '1'..
    

    【讨论】:

    • 它给了我 "undefined" 。请帮忙
    【解决方案3】:

    数据包含 FRELD6 尝试:

    var reldte;
    var sdata = JSON.parse(data);
     $(sdata).each(function () {
            reldte = RefineDate(this.FRELD6.toString());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2020-06-02
      相关资源
      最近更新 更多