Search code examples
pythonjsonlistdictionaryprtg

How do I convert a JSON file into a list of dicts?


So I have a JSON file with the following contents:

{"prtg-version":"17.1.29.1531","treesize":8,"probes":
    [
        {"objid":1,"name":"ASHBURN CORE"},
        {"objid":30201,"name":"GRAND RAPIDS PROBE"},
        {"objid":2,"name":"Cluster Probe"},
        {"objid":6015,"name":"AWS Oregon"},
        {"objid":2666,"name":"ASHBURN PROBE"},
        {"objid":9607,"name":"HERNDON PROBE"},
        {"objid":9218,"name":"DENVER"},
        {"objid":7259,"name":"AWS Ohio"}
    ]
}

I want to use this data in a python script but first I need to convert this JSON into a list of dicts and then store that list of dicts to a variable in Python. Also, I am fetching this JSON file using an API call from a PRTG server if that helps at all. I've also imported the JSON module.

Essentially, if I can strip off the outer dictionary, I will be left with a list of dicts that already follows Python format. Any ideas how to do that?


Solution

  • This might be helpful

    import json
    
    a = '{"prtg-version":"17.1.29.1531","treesize":8,"probes":[{"objid":1,"name":"ASHBURN CORE"},{"objid":30201,"name":"GRAND RAPIDS PROBE"},{"objid":2,"name":"Cluster Probe"},{"objid":6015,"name":"AWS Oregon"},{"objid":2666,"name":"ASHBURN PROBE"},{"objid":9607,"name":"HERNDON PROBE"},{"objid":9218,"name":"DENVER"},{"objid":7259,"name":"AWS Ohio"}]}'
    
    data = json.loads(a)
    
    
    
    for a in data:
      print(a,data[a])
    

    I am converting the response to json and iterating over it in the for loop