【问题标题】:Extracting specific elements from multiple JSON files and adding into single Excel从多个 JSON 文件中提取特定元素并添加到单个 Excel 中
【发布时间】:2021-08-27 12:43:29
【问题描述】:

所以,基本上我有两个 JSON 文件,我只需要从中提取“值”并将其添加到单个 Excel 工作表中。

JSON 文件 1

{
 "flower": {
    "price": {
        "type": "good",
        "value": 5282.0,
        "direction": "up"
    }
   },
 "furniture": {
    "price": {
        "type": "comfy",
        "value": 9074.0,
        "direction": "down"
    }
   }
 }

JSON 文件 2

{
 "flower": {
    "price": {
        "type": "good",
        "value": 827.0,
        "direction": "up"
    }
   },
 "furniture": {
    "price": {
        "type": "comfy",
        "value": 468.0,
        "direction": "down"
    }
   }
 }

现在,Excel sheet 中的输出应如下所示

因此,为了解决这个问题,这里是到目前为止的代码,其中 JSON 文件 1 是 json.json,文件 2 是 json12.json

import json
import pandas as pd

with open('json.json', 'r') as f: data = json.load(f)
with open('json12.json', 'r') as f: data1 = json.load(f)

data = [{'key': k, 'value1': v['price']['value']} for k, v in data.items() if k in ['flower' , 'furniture']]
print(data)
data1 = [{'key': k, 'value2': v['price']['value']} for k, v in data.items() if k in ['flower' , 'furniture']]
print(data1)

df = pd.DataFrame(data).set_index('key') 
df = pd.DataFrame(data1).set_index('key') 
df.to_excel('xcel.xlsx')

运行此程序后,我没有得到所需的输出...所以,请帮助我,因为我是学习 python 的新手,所以很难找到正确的方法..

【问题讨论】:

  • 嘿@sherkhan,你试过我的解决方案了吗?我认为它有效。如果是,请验证它
  • @Borja_042 如果我想在相邻单元格中添加 value1 和 value2 并显示....如果可能的话,我们可以有那种输出吗?
  • 你好@sherkhan,当然可以。假设 jsons 是我下面的代码产生的数据框的名称,您可以很容易地添加值: jsons['valued_Added'] = jsons.value1 + jsons.value2

标签: python json excel pandas


【解决方案1】:

我相信这段代码可以满足您的要求(如果 j1 和 j2 是您显示的 json):

v1s = [j1['flower']['price']['value'], j1['furniture']['price']['value']]
v2s = [j2['flower']['price']['value'], j2['furniture']['price']['value']]
index = ['flower', 'furniture']

pd.DataFrame({'value1': v1s, 'value2': v2s, 'key': index}).set_index('key')

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多