[Answered ]-Json formatting trouble, when updating or editing my json file

1👍

The issue is probably related with the way you are saving your files. You should add a json_file.truncate() after the json_file.seek(0), so it will clean the file contents before saving anything new.

When you seek the 0 position, you just change the cursor, but the content of the file will still be the same, so if there was something bigger on the file, it will stay there.
Example:

products.json

{"foo":"bar"}

.

with open("products.json", "r+") as json_file:
    json_file.seek(0)
    json_file.write(json.dumps({"foo":"b"})) # Will write {"foo":"b"} to the file

instead of resulting a file with {"foo":"b"}, the products.json file content will be {"foo":"b"}"}

1👍

UPDATE: It appears you are intending to read in the file, update the contents, then replace the file contents with the updated structure. Given that, I’ve made two more suggested changes to your code below, explicitly opening the file, reading in the data, closing the file, then at the end opening the file for writing, putting the new structure into it, and closing the file. This should ensure the file itself is clean each time.


You might consider that:

    products["products"][pk] = instance.returnAsJSON()

may be adding extraneous brackets as part of the JSON return.

Also, rather than use:

    products = json.loads(json_file.read()) 
    json_file.write(json.dumps(products))

Try using:

    products = json.load(json_file)
    json.dump(products, json_file)

As in:

@receiver(post_save, sender=item, dispatch_uid="update_json")
def update_stock(sender, instance, **kwargs):
    pk = str(instance.pk)
    with open(MEDIA_ROOT + '/json/products.json', 'r') as json_input_file:
        products = json.load(json_file); json_input_file.closed
    print(products) <--- 1
    products["products"].pop(pk, None)
    print(products) <--- 2
    products["products"][pk] = instance.returnAsJSON()
    print(products) <--- 3
    with open(MEDIA_ROOT + '/json/products.json', 'w') as json_output_file:
        json.dump(products, json_output_file); json_output_file.closed

Note I’ve also removed the:

         json_file.seek(0)

As I don’t see the need here. If it turns out my tired eyes are missing something, please ignore, and perhaps let me know.

You may find these clean things up a little.

Leave a comment