简体   繁体   中英

How to obtained the json from the dataframe with the column names for every row as a key using python

I want the json data from the dataframe where I need to have the column name as key for every row using python.

Name   Age  Qualification
  A     35     MCA
  B     30     Phd
  C     28     Msc

From the above dataframe I want the json. I don't want to convert it into dictionary. it should row-wise json data. How to get the json in the below format?

{'Name': 'A' , 'Age': 35 , 'Qualification':'MCA'}
{'Name': 'B' , 'Age': 30 , 'Qualification':'Phd'}
{'Name': 'C' , 'Age': 28 , 'Qualification':'Msc'}
json_str_list = [] 
for i in df.index:
    json_str = df.loc[i].to_json()
    json_str_list.append(json_str)

The above code will solve your question. If you want it to be a JSON object you can import json and just do,

json_obj = json.loads(json_str)

Use DataFrame.to_json with parameters orient='records' and lines=True :

df.to_json(file, orient='records', lines=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM