1

I am new to json file handling. I have a below json file

{"loanAccount":{"openAccount":[{"accountNumber":"986985874","accountOpenDate":"2020-02-045-11:00","accountCode":"NA","relationship":"Main account","loanTerm":"120"}]}}

I want to convert this into dataframe. I am using the below code :

import pandas as pd
from pandas.io.json import json_normalize

data1 = pd.read_json (r'./DLResponse1.json',lines=True)
df = pd.DataFrame.from_dict(data1, orient='columns')

This is giving me the below output :

index   loanAccount
0       {'openAccount': [{'accountNumber': '986985874', 'accountOpenDate': '2020-02-045-11:00', 'accountCode': 'NA', 'relationship': 'Main account', 'loanTerm': '120'}]}}

However I want to extract in the below format :

loanAccount  openAccount  accountNumber  accountOpenDate    accountCode  relationship  loanTerm
                          986985874      2020-02-045-11:00   NA          Main account  120
1
  • there is a problem with your json file Commented Apr 1, 2020 at 19:04

1 Answer 1

2

you may use:

# s is your json, you can read from file
pd.DataFrame(s["loanAccount"]["openAccount"])

output:

enter image description here

if you want also to have the other json keys as columns you may use:

pd.DataFrame([{"loanAccount": '', "openAccount": '', **s["loanAccount"]["openAccount"][0]}])

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

I tried your code but unfortunately I am not getting the expected output. Getting error KeyError: 'openAccount'. I first loaded my json file which I mentioned in my query and then I used your code.However I tried this x =pd.DataFrame([{"loanAccount": '', **data1["loanAccount"][0]}]) but this also seems not working for me. I am new to json file handling so could not able to resolve this error.
maybe you have a diffrent json than the one from question ? can you check again ?
you should read the json like : with open('data.json') as f: data = json.load(f)
I used this command to read json file data1 = pd.read_json (r'./DLResponse1.json',lines=True) and DLResponse1 file contains exactly what I have mentioned in my above json data.
with open('data.json') as f: data = json.load(f) with this reading method, it works for me.. thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.