0

I have a dataframe with multiple levels of index. I would like to output it as nested json for consumption by other scripts. Here is a simple example

enter image description here

I would like to output the above image as

{
  "a": {
    "1": {"foo":6, "bar": 0}, 
    "2": {"foo":0, "bar": 2}, 
    "3": {"foo":5, "bar": 0}
  },
  "b": {
    "1": {/*...*/}, 
    "2": {/*...*/}, 
    "3": {/*...*/}
  },
  "c": {/*...*/},
}

Unfortunately just using .to_json() gives me two objects with the values of the columns, which isn't very useful to my consuming script

enter image description here

I can get closer if I transpose it first, but I still lack the desired nesting.

enter image description here

Is there any way to accomplish this? I'm trying to google the results but all the suggestions I'm finding are about READING nested json.

Sidney
  • 624
  • 7
  • 20
  • Duplicate of https://stackoverflow.com/questions/17043860/how-to-dump-a-dict-to-a-json-file – Sidney Jun 23 '23 at 17:46
  • Does this answer your question? [How to dump a dict to a JSON file?](https://stackoverflow.com/questions/17043860/how-to-dump-a-dict-to-a-json-file) – Laurent Jun 24 '23 at 06:34

0 Answers0