How can I transform a pandas df to this kind of json structure?

Let’s say I have a pandas df like this:

| name   | color of clothing | age |occupation|
| John   | yellow            | 34  | janitor  |
| Carl   | red               | 27  | doctor   |
| Claire | green             | 33  | teacher  |
| Lisa   | blue              | 21  | Student  |
|........|...................| ....|..........|

I would like to transform it in a json format like this:

[
{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
},
{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
},
{ "name": "Claire",
"color of clothing": "green",
"age":"33",
"occupation": "teacher"
},
{ "name": "Lisa",
"color of clothing": "blue",
"age":"21",
"occupation": "student"
}
]

How can I do this? The nearest match I had was using df.to_json(orient="index") but what I’ve got was a structure like this:

{"0":{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
}
},
"1":{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
}}
...

Would be really thankful for any help!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use df.to_dict('records')

>>> df
   a  b  c  d
0  1  1  1  1
1  2  2  2  2
>>> df.to_dict('records')
[{'a': 1, 'b': 1, 'c': 1, 'd': 1}, {'a': 2, 'b': 2, 'c': 2, 'd': 2}]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x