简体   繁体   中英

python: I need to append a file with json but it does not output a valid json

I am working on a file which prints json encoded messages

{
        "Status": "Non_Malicious",
        "alert_level": "Low",
        "alert_count": 1,
        "alert": "",
        "hosts_alert": ""
    }

NOTE the file is appended every message as above

def jsonconvert(new_line, set_alert_level, set_status, hosts_alert, ip_address_alert, alert_count, title):

    data = {}
    data['alert_description'] = new_line
    data['alert_level'] = set_alert_level
    data['Status'] = set_status
    data['hosts_alert'] = hosts_alert
    data['alert'] = title

    json_data = json.dumps(data)

    file_write = open("json_file", 'a')
    file_write.write(json_data+','+'\n')
    file_write.close() 

But in order to make it valid, i need to append it as such bellow : which im not sure how to get it done.

{
    "isoc": [{
        "Status": "Non_Malicious",
        "alert_level": "Low",
        "alert_count": 1,
        "alert": "",
        "hosts_alert": ""
    }, {
        "Status": "Non_Malicious",
        "alert_level": "Low",
        "alert_count": 1,
        "alert": "",
        "hosts_alert": ""
    }]
}

You can't make valid JSON files by just appending. This is not just a problem with Python.
That's because, as you noted, every open bracket must be closed, and there should not be trailing commas.

Here are some possible solutions that come to my mind:

  • Use another file format that does not suffer for this limitation, like CSV or YAML or even plain text
  • Don't append to a file, but use a database instead
  • Keep all the contents in memory and dump them all at once in a single JSON file, overwriting it every time
  • At every append operation, delete the closing brackets, append your data then re-add them again. This solution is a ugly hack, so I don't advice it, but it works.

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