简体   繁体   中英

How can I format json via python?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM