Python: Read JSON From a File into Dictionary

Python Random

Read in JSON from a file and convert into a Dictionary

#!/usr/bin/env python

import json

f = open('data.json')
data = json.load(f)
data = json.dumps(data,indent=2)

# Prints the Imported JSON
print(data)

# Loads JSON into a Dictionary
objArrayInfoDict = json.loads(data)
print(objArrayInfoDict)

For example I was testing getting data from the Slack service status API, so wanted to simulate broken-ness to test my script was working correctly. I did this by creating a file with a sample set of JSON that showed a problem, as I could easily get JSON of when it was working, which was the case as I was writing the script!

Example: data.json file

  {
    "status": "active",
    "date_created": "2019-04-09T07:35:46-07:00",
    "date_updated": "2019-04-09T07:35:46-07:00",
    "active_incidents": [
      {
        "id": "1",
        "date_created": "2018-09-07T14:35:00-07:00",
        "date_updated": "2018-09-07T18:34:15-07:00",
        "title": "One thing is broken",
        "type": "incident",
        "status": "active",
        "url": "https://status.domain.com/issue1/",
        "services": [
          "Apps/Integrations/APIs"
        ],
        "notes": [
          {
            "date_created": "2018-09-07T18:34:15-07:00",
            "body": "Its all gone wrong!"
          }
        ]
      },
      {
        "id": "2",
        "date_created": "2018-09-07T14:35:00-07:00",
        "date_updated": "2018-09-07T18:34:15-07:00",
        "title": "Its all gone wrong!",
        "type": "incident",
        "status": "active",
        "url": "https://status.domain.com/issue2/",
        "services": [
          "Apps/Integrations/APIs"
        ],
        "notes": [
          {
            "date_created": "2018-09-07T18:34:15-07:00",
            "body": "Its all on fire!"
          }
        ]
      }
    ]
  }

Leave a Reply

Your email address will not be published. Required fields are marked *