Skip to content

Round trip load/dump with comment preservation #29

@erwanp

Description

@erwanp

Hello @spyoungtech

I'm looking for a JSON parser with round-trip support for comments to use as a configuration file in an open-source physics code.

JSON5 looks like a great candidate; and the doc suggests you have round-trip comment support already ; but I couldnt get it to work in my case.

Example of use-case :

import json5     # !pip install json-five

jsonfilecontent = """{
"database": {                       /* database key, stores all databases */
    "HITEMP-CO2": {                 /* a database name */
    "path": [
        "PATH/TO/1",
        "PATH/TO/2"]}
  }
}"""

config = json5.loads(jsonfilecontent )
config["NEW"] = {"path":["PATH/TO/3"]}      # EXPECTED : edit as a dict 
with open("config.json", "w") as f:
    json5.dump(JSONCDict, f)                    # EXPECTED : dump and keep comments

With json5 the above does not work yet; I understand it's because #12 is not implemented.

I tried based on the round-trip comment example :

from json5.loader import loads, ModelLoader
from json5.dumper import dump, ModelDumper
from json5.model import BlockComment

model = loads(jsonfilecontent, loader=ModelLoader())           # loaded ok
with open("config.json", "w") as f:
    dump(model, f, dumper=ModelDumper())           # comments preserved

It works fine, comments are preserved. However, how can I insert a full Python dictionary as a new entry in the model ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions