0

I'm trying to append some data into a JSON file inside python. It should add the CVE-ID into my customer JSON file.

I wasn't able to solve this by myself. If I print my dict after appending it shows the expected result. But it seems, that the file will not be written after the append. I have also tried to use json.dump() after the "appending-line" - but also without success.

At the moment my code looks like this:

with open("test.json", "r+") as customerdata:
    customers_json = json.load(customerdata)

# some other code here...

if cve["cve"]["CVE_data_meta"]["ID"] not in customer["customer"]["already-sent-cve"]:
                customers_json["customers"][0]["customer"]["already-sent-cve"].append(cve["cve"]["CVE_data_meta"]["ID"])

My JSON file looks like this:

    {
        "customers":[
            {
                "customer":{
                    "id":"1",
                    "company-name":"test GmbH",
                    "alert-email":"[email protected]",
                    "using":[
                        "xxx",
                        "xyz"
                    ],
                    "already-sent-cve":[
                        "CVE-2013-3738"
                        # here new CVE
                    ]
                }
            },
        {
            "customer":{
                "id":"2",
                  ...
          }
    ]
}

FYI: There is another JSON file with the CVE's from which file I'm collecting the data.

Any suggestions how to solve this?

Regards.

EDIT:

Was able to solve this:

with open("test.json", "w") as customerdata:
    customers_json["customers"][0]["customer"]["already-sent-cve"].append(cve["cve"]["CVE_data_meta"]["ID"])
    json.dump(customers_json, customerdata, indent=2)
2
  • 1
    can you please share code where you are using json.dump Commented Feb 27, 2020 at 8:23
  • Your edit should be posted as an answer -- not as an update to the question Commented Feb 27, 2020 at 10:19

1 Answer 1

1

You need to write the data back to the file:

with open('test.json', 'w') as customerdata:
    json.dump(customers_json, customerdata)
Sign up to request clarification or add additional context in comments.

3 Comments

So but I need still the append operation? I'm not sure how I can only write back the new element or is it only possible to wirte back a complete JSON file (and not just add the needed element)?
you need to write back the complete JSON file
Ahh, got it. This was my mistake. I thought I'm able to write back only a specific value. Now it seems to be working. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.