如何访问JSON文件的叶节点,获取所有客户2022年的sales_value,然后用Python进行求和?

oprakyz7  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(137)

{ "customer_data": [ { "name": "John Smith", "age": 35, "email": "johnsmith@gmail.com", "phone": "0413-535-124", "sales_value": [ { "year": "2022", "sales_value": 2000 }, { "year": "2023", "sales_value": 3000 } ] }, { "name": "Jane Doe", "age": 28, "email": "janedoe@yahoo.com", "phone": "0401-655-568", "sales_value": [ { "year": "2022", "sales_value": 2000 }, { "year": "2023", "sales_value": 3000 } ] }, { "name": "Bob Johnson", "age": 42, "email": "bjohnson@hotmail.com", "phone": "0433-515-912", "sales_value": [ { "year": "2022", "sales_value": 2000 }, { "year": "2023", "sales_value": 3000 } ] }, { "name": "Bob2 Johnson", "age": 42, "email": "bjohnson@hotmail.com", "phone": "0433-515-912", "sales_value": [ { "year": "2022", "sales_value": 2000 }, { "year": "2023", "sales_value": 3000 } ] }, { "name": "Bob3 Johnson", "age": 42, "email": "bjohnson@hotmail.com", "phone": "0433-515-912", "sales_value": [ { "year": "2022", "sales_value": 2000 }, { "year": "2023", "sales_value": 3000 } ] } ] }
使用上面的json文件需要在python中计算2022年的sales_value。请问你能指导我如何得到叶节点和计算2022年的总销售额吗
我已经尝试获取叶节点

wgx48brx

wgx48brx1#

如果你确定json会包含每个客户的'sales_value'字段,那么你可以尝试以下操作,这应该是不言自明的:

import json
with open('file.json', 'r') as f:
    data = json.load(f)
total_sales_value = 0
for customer in data['customer_data']:
    for sales in customer['sales_value']:
        if sales['year']=='2022':
            total_sales_value += sales['sales_value']

至于可读性较低的一个衬垫:

sum([sales['sales_value'] for customer in data['customer_data'] for sales in customer['sales_value'] if sales['year']=='2022'])

输出:

10000

相关问题