有条件地解析json

2024-04-25 22:57:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用python从json数组中提取一个值。如何在特定日期获取"energy"的值?以下是json的外观:

{
  "emeter": {
    "get_daystat": {
      "day_list": [
        { "year": 2016, "month": 10, "day": 1, "energy": 0.651000 },
        { "year": 2016, "month": 10, "day": 2, "energy": 0.349000 },
        { "year": 2016, "month": 10, "day": 3, "energy": 0.481000 }
      ],
      "err_code": 0
    }
  }
}

例如,使用:

^{pr2}$

如何提取"energy""energy"值?在


Tags: jsongetcode数组yearlistenergy外观
2条回答

parsed_json将有一个python dict。您可以通过简单的线性搜索访问day_list数组。在

def get_energy_value_by_date(obj, year, month, day):   
    for value in obj['emeter']['get_daystat']['day_list']:
        if value['year'] == year and value['month'] == month and value['day'] == day:
            return value['energy']


energy = get_energy_value_by_date(parsed_json, 2016, 10, 2)

您可以对数据进行线性搜索:

def get_energy(data, year, month, day):
    for date in data['emeter']['get_daystat']['day_list']:
        if(date['year'] == year
           and date['month'] == month
           and date['day'] == day):
            return date['energy']

json_data = {
  "emeter": {
    "get_daystat": {
      "day_list": [
        { "year": 2016, "month": 10, "day": 1, "energy": 0.651000 },
        { "year": 2016, "month": 10, "day": 2, "energy": 0.349000 },
        { "year": 2016, "month": 10, "day": 3, "energy": 0.481000 }
      ],
      "err_code": 0
    }
  }
}

print('{:1.6f}'.format(get_energy(json_data, 2016, 10, 2)))  #  > 0.349000

如果没有匹配的日期,函数将有效地返回None。在

*更新*

如果您在"day_list"中有很多天是按日期排序的(如您的示例所示),那么利用这一点并进行二元搜索比线性搜索更快。Python包含^{}模块,该模块可用于执行简单的二进制搜索。不幸的是,其中没有一个函数像^{}函数那样采用可选参数来控制比较。在

但是,可以通过查看模块的source code并编写自己的搜索函数来克服这一问题,如下所示:

^{pr2}$

输出:

0.651000
0.349000
0.481000
Traceback (most recent call last):
  File "conditionally-parsing-json.py", line 67, in <module>
    print('{:1.6f}'.format(get_energy2(json_data, 2016, 10, 4)))  #  > ValueError
  File "conditionally-parsing-json.py", line 62, in get_energy2
    raise ValueError('date not found')
ValueError: date not found

相关问题 更多 >