Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to modify a JSON file using Python without losing comments in the file

I have a settings.json file full with useful comments (sometimes C-style and sometimes Python), and I’m programmatically modifying them with e.g. json library, but when I save the modified one I lose all the comments explaining the fields. Another inconvenience is losing the indentations and spacing therein.

Is there a ‘neat’ way of modifying the file programmatically?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Standard json files cannot possibly have comments and still be compliant json.

There is another format that was designed to overcome this problem: json5. It has libraries designed to keep json5 properties like comments intact – you can python library for it here.

Another approach is to keep using standard JSON but add "doc" fields for each JSON block in question. In this case, doc field(s) become data payload and will survive any transformation. For example, Apache Avro is using doc fields to document avro schema.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading