pythonjsonpandasto-jsonconvertto-json

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!


Solution

  • 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}]