Alex Deft
Alex Deft

Reputation: 2787

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?

Upvotes: 1

Views: 922

Answers (1)

mvp
mvp

Reputation: 116337

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.

Upvotes: 3

Related Questions