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

Time:01-01

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?

CodePudding user response:

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.

  • Related