export list of dictionaries to JSON with Python

Viewed 145

I have one dictionary that I have managed to export to JSON format

{
"Services": [
    {
        "Name": "Service1",
        "Products": {
            "product1": "yes",
            "product2": "yes",
            "product3": "no",
            "product4": "yes",
            "product5": "yes"
        }
    }
]

}

The code that I use is the following :

end_result["Services"] = lst
    with open("json_test.json","w") as outputfile:
        json.dump(end_result,outputfile,indent = 4)

where end result is the dictionary that I want to write to the JSON file. This block of code is part of a really big loop.All the dictionaries are created in this loop. For the first dictionary, I have managed to export it to JSON. I want for the second and third dictionary to export it to JSON.

The result would be like this:

   {
"Services": [
    {
        "Name": "Service1",
        "Products": {
            "product1": "yes",
            "product2": "yes",
            "product3": "no",
            "product4": "yes",
            "product5": "yes"
        }
    }
]

}

   {
    "Services": [
        {
            "Name": "Service1",
            "Products": {
                "product1": "yes",
                "product2": "yes",
                "product3": "no",
                "product4": "yes",
                "product5": "yes"
            }
        }
    ]
}

   {
    "Services": [
        {
            "Name": "Service1",
            "Products": {
                "product1": "yes",
                "product2": "yes",
                "product3": "no",
                "product4": "yes",
                "product5": "yes"
            }
        }
    ]
}

All the dictionaries must be on the same JSON file. The list of dictionaries can consist of one dictionary or more. That depends on the findings of the algorith. So far, I have only a dictionary in each list but it can have more dictionaries. For instance, I can have service1 and service2 in a list of dictionaries.

0 Answers
Related