使用 json_normalise 展平 JSON 文件并选择要转换为 excel sheet 的特定元素(附示例)

flattening JSON file using json_normalise and choosing specific elements to convert to an excel sheet (Sample Attached)

{
  "currency": {
    "Wpn": {
      "units": "KB_per_sec",
      "type": "scalar", 
      "value": 528922.0, 
      "direction": "up"
  }
}, 
  "catalyst": {
    "Wpn": {
      "units": "ns", 
      "type": "scalar", 
      "value": 70144.0, 
      "direction": "down"
  }
}, 
  "common": {
    "Wpn": {
      "units": "ns", 
      "type": "scalar", 
      "value": 90624.0, 
      "direction": "down"
  }
 }
}

所以我基本上必须将嵌套的 json 转换为 excel,为此我的方法是使用 json_normalise 展平 json 文件,但因为我是新手所有这些...我似乎总是以 KeyError 结束...

到目前为止,这是我的代码,假设该文件被命名为 json.json

import requests

from pandas import json_normalize

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

df = pd.DataFrame(sum([i[['Wpn'], ['value']] for i in data], []))

df.to_excel('Ai.xlsx')

我正在尝试在 excel sheet consisting of currency and common along with their resp. values as an output

上获取输出

我知道,有很多类似的问题,但请相信我,我已经尝试了大部分问题,但我没有得到任何理想的输出...请帮我解决这个问题

尝试:

import json
import pandas as pd

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


data = [{'key': k, 'wpn_value': v['Wpn']['value']} for k, v in data.items()]
print(data)
# here, the variable data looks like
# [{'key': 'currency', 'wpn_value': 528922.0}, {'key': 'catalyst', 'wpn_value': 70144.0}, {'key': 'common', 'wpn_value': 90624.0}]

df = pd.DataFrame(data).set_index('key') # set_index() optional
df.to_excel('Ai.xlsx')

结果看起来像

key wpn_value
currency 528922
catalyst 70144
common 90624