Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

python - Export JSON object to excel

I have a pretty messed up JSON object like this -

{
"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"
  }
}
}

I want to have excel sheet like this-

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

I tried to convert it into pandas dataframe with the help of json_normalize but it's showing all the data in 1 row only. This is the code used

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

I tried using swapLevel, reordering etc. but didn't work out. I am a beginner in Python. Please help!

question from:https://stackoverflow.com/questions/65599423/export-json-object-to-excel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to get this to work, I had to wrap your example above in a list and piece it together.

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']

Output

  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

If you need to put in a loop, you'll just have to rework the code to perhaps append rows as you go rather than concatenating like I've done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...