Home > Enterprise >  How can I format json via python?
How can I format json via python?

Time:06-20

I have a very basic problem that I can't figure out. I keep getting a "End of file expected.json" when trying to write object data to a json file. I was wondering how I can fix that? I do it by writing in a for loop. Not sure how I can format.

This is the code in question

with open("data.json", "w") as outfile:
    for x,y in structures.infrastructures.items():
        outfile.write(Sector(x, y["Depended on by"],y["Depends on"], y["Sub sections"]).toJson())

and this is the output

{
    "name": "Chemical",
    "depended_on": [
        "Critical Manufacturing",
        "Nuclear Reactors, Waste, and Material Management",
        "Commercial",
        "Healthcare and Public Health",
        "Food and Agriculture",
        "Energy"
    ],
    "depends_on": [
        "Emergency Services",
        "Energy",
        "Food and Agriculture",
        "Healthcare and Public Health",
        "Information Technology",
        "Nuclear Reactors, Waste, and Material Management",
        "Transportation Systems",
        "Water"
    ],
    "sub_sections": [
        "Chemical Plants",
        "Chemical Refineries",
        "Labs"
    ],
    "Status": 0,
    "Strain": 0
}{                                  -> this is where the error is
    "name": "Commercial",
    "depended_on": [
    ....
    ....
    etc

This is my toJson method:

    def toJson(self):
        return json.dumps(self, default=lambda o: o.__dict__, indent=4)

But yeah how can I implement it where my object data is written in JSON format?

CodePudding user response:

A valid json file can only contain one object. Collect your data into a list and write it with a single call, or simulate the format with your code.

CodePudding user response:

You have to use a function to parse the .json

I hope this helps

https://scriptcrunch.com/parse-json-file-using-python/#:~:text=How To Parse JSON File Content Using Python,also loop through all the JSON objects.

  • Related