【问题标题】:Export JSON object to excel将 JSON 对象导出到 Excel
【发布时间】:2021-04-12 09:57:45
【问题描述】:

我有一个像这样非常混乱的 JSON 对象 -

{
"LDL Cholesterol": {
  "displayName": {
    "en": "LDL Cholesterol",
    "hi": "kls"
  },
  "sliderType": "NHHHH",
  "high": 160,
  "text": {
    "en": "LDL",
    "hi": "ldd"
  }
},

"HDL/LDL Cholesterol Ratio": {
  "displayName": {
    "en": "HDL : LDL ratio",
    "hi": "klas"
  },
  "sliderType": "LN",
  "lowThresh": 0.33,
  "text": {
    "en": "",
    "hi": "jla"
  }
}
}

我想要这样的excel表格-

Test Name                |sliderType|high|lowThresh|en.displayName |en.text|hi.displayName|hi.text
LDL Cholesterol          | NHHHH    |160 |         |LDL Cholesterol|  LDL  |   kls        |ldd
HDL/LDL Cholesterol Ratio| LN       |    |  0.33   |HDL : LDL ratio|       |   klas       |jla

我尝试在 json_normalize 的帮助下将其转换为 pandas 数据框,但它仅在 1 行中显示所有数据。 这是使用的代码

f=open('path_to_file','rb')
data = json.load(f)
df = pandas.json_normalize(data)

我尝试使用 swapLevel、重新排序等,但没有成功。 我是 Python 的初学者。请帮忙!

【问题讨论】:

  • 发布您的代码,以便我们查看问题所在。

标签: python json excel pandas dataframe


【解决方案1】:

这是加载到 pandas 的语法

data = json.loads(your_input)
df = pd.json_normalize(data['results'])

【讨论】:

    【解决方案2】:

    为了让它工作,我必须将上面的示例包装在一个列表中并将其拼凑在一起。

    d={
    "LDL Cholesterol": {
      "displayName": {
        "en": "LDL Cholesterol",
        "hi": "kls"
      },
      "sliderType": "NHHHH",
      "high": 160,
      "text": {
        "en": "LDL",
        "hi": "ldd"
      }
    },
    
    "HDL/LDL Cholesterol Ratio": {
      "displayName": {
        "en": "HDL : LDL ratio",
        "hi": "klas"
      },
      "sliderType": "LN",
      "lowThresh": 0.33,
      "text": {
        "en": "",
        "hi": "jla"
      }
    }
    }
    dl =[d]
    df1 = pd.json_normalize(dl[0]['LDL Cholesterol'])
    df2 = pd.json_normalize(dl[0]['HDL/LDL Cholesterol Ratio'])
    df = pd.concat([df1, df2], axis=0)
    df['Test Name'] = ['LDL Cholesterol', 'HDL/LDL Cholesterol Ratio']
    

    输出

      sliderType   high   displayName.en displayName.hi text.en text.hi  lowThresh                  Test Name
    0      NHHHH  160.0  LDL Cholesterol            kls     LDL     ldd        NaN            LDL Cholesterol
    0         LN    NaN  HDL : LDL ratio           klas             jla       0.33  HDL/LDL Cholesterol Ratio
    

    如果您需要放入一个循环,您只需要重新编写代码以在执行过程中添加行,而不是像我所做的那样连接。

    【讨论】:

      猜你喜欢
      • 2023-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2016-02-20
      • 2015-08-10
      相关资源
      最近更新 更多