从json获取元素

时间:2015-08-22 22:45:14

标签: python json parsing constructor

我是python中的新手,我正在尝试实现一个小的Bellman-ford算法。我在json中得到了不同货币的汇率,看起来像这样:

{"USD_JPY": "88.1911719", "USD_USD": "1.0000000", "JPY_EUR": "0.0086441", "BTC_USD": "122.5311820", "JPY_BTC": "0.0000923", "USD_EUR": "0.6695743", "EUR_USD": "1.2624079", "EUR_JPY": "129.3438373", "JPY_USD": "0.0111120", "BTC_BTC": "1.0000000", "EUR_BTC": "0.0110526", "BTC_JPY": "12543.0532689", "JPY_JPY": "1.0000000", "BTC_EUR": "90.3821109", "EUR_EUR": "1.0000000", "USD_BTC": "0.0071458"}

我试图以这种方式实例化我的对象,但它似乎无法正常工作,即使它有工作我认为它不是真正有效(如果货币的顺序改变我搞砸了)

def __init__ (self, rates):    
    res = json.load(rates)
    self.EURToEUR = 1.000000
    self.USDToUSD = 1.000000
    self.JPYToJPY = 1.000000
    self.BTCToBTC = 1.000000
    self.EURToUSD = json[6]['EUR_USD']
    self.EURToJPY = json[7]['EUR_JPY']
    self.EURToBTC = json[10]['EUR_BTC']
    self.USDToEUR = json[5]['USD_EUR']
    self.USDToBTC = json[15]['USD_BTC']
    self.USDToJPY = json[0]['USD_JPY']
    self.BTCToEUR = json[13]['BTC_EUR']
    self.BTCToJPY = json[11]['BTC_JPY']
    self.BTCToUSD = json[3]['BTC_USD']
    self.JPYToEUR = json[2]['JPY_EUR']
    self.JPYToUSD = json[8]['JPY_USD']
    self.JPYToBTC = json[4]['JPY_BTC']

如果你们能告诉我它是如何工作的,并且有效地阅读我的JSON,我将很高兴。

2 个答案:

答案 0 :(得分:2)

您不需要使用索引访问json对象。关键是你所需要的。此外,您要访问var item = ''; ,这是您加载的对象,而不是res,模块的名称

json

这一点:

self.EURToUSD = res['EUR_USD']

答案 1 :(得分:1)

如何使用ofSubLists

from collections import namedtuple

data = {"USD_JPY": "88.1911719", "USD_USD": "1.0000000", "JPY_EUR": "0.0086441", "BTC_USD": "122.5311820", "JPY_BTC": "0.0000923", "USD_EUR": "0.6695743", "EUR_USD": "1.2624079", "EUR_JPY": "129.3438373", "JPY_USD": "0.0111120", "BTC_BTC": "1.0000000", "EUR_BTC": "0.0110526", "BTC_JPY": "12543.0532689", "JPY_JPY": "1.0000000", "BTC_EUR": "90.3821109", "EUR_EUR": "1.0000000", "USD_BTC": "0.0071458"}
Currency = namedtuple('Currency', data.keys())
currency = Currency(**data)

然后你得到这样的数据:

>>> currency.USD_JPY
'88.1911719'
>>>> currency.USD_USD
'1.0000000'

所以,在你的例子中,它将是:

def __init__ (self, data):       
    Currency = namedtuple('Currency', data.keys())
    self.currency = Currency(**data)