How to format/print a nested Json in Python

Viewed 32

I'm not sure if i should just approach this by removing the special characters and i guess iterate through the dictionary and somehow organize them. Kidnly let me know the right way to do this. Thanks The current JSON string is like that

dict_list =  {
"CIS3760": {
  "sections": [
      {
    "number": "0101",
    "professor": "greg",
    "times": [
      {
      "days": "MWF",
      "time": "9:00",
      "type": "class"
    },
      {
      "days": "MWF",
      "time": "9:00",
      "type": "class"
    }
    ]
  },
  {
      "number": "0202",
      "professor": "RUBY",
      "times": [
      {
      "days": "tth",
      "time": "10:00",
      "type": "lab"
    },
      {
      "days": "tth",
      "time": "9:00",
      "type": "class"
    }
    ]
  }
  ]
}

} and im trying to get it to look like this

 CIS3760s

   Sections are
       number: 0101
       professor: greg
       times

           days:MWF
           time: 9:00
           type: class

           days: MWF
           time: 9:00
           type: class
1 Answers

Try this:

val = json.dumps(dict_list, indent=2)
temp = re.sub(r'[\"\]\[\{\},]', '', val).strip()
final = ''.join(temp.split("      \n      \n"))
print(final)

OUTPUT

CIS3760:
    sections:

        number: 0101
        professor: greg
        times:

            days: MWF
            time: 9:00
            type: class


            days: MWF
            time: 9:00
            type: class


        number: 0202
        professor: RUBY
        times:

            days: tth
            time: 10:00
            type: lab


            days: tth
            time: 9:00
            type: class
Related