1

Is it possible to custom-encode dictionary values to JSON based on the key name?

Lets say I have

mydict = {
    "mylist1": ["a", "b", "c"],
    "mylist2": ["a", "b", "c"],
    "mylist3": ["a", "b", "c"]}

I would like to dump "mylist1" without indents, just based on its name, but the rest of the dict with the regular json encoder. So something like:

{
    "mylist1": [ "a","b","c"],
    "mylist2": [
        "a",
        "b",
        "c"
    ],
    "mylist3": [
        "a",
        "b",
        "c"
    ]
}

I was inspired by this SO question, where an "indicator-class" is used to flag the dict entries. This would work for my case too, but my JSON files are opened, the content parsed and modified, and then saved again, so that the indicator class (NoIndent) is lost.

If key-name based encoding is too involved I would already be happy if I could dump ALL lists (and arrays!) without indentation, or as string. I tried this, but it didn't work (the custom encoder wouldn't fire up):

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return str(list(obj))
        elif isinstance(obj, list):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

EDIT: I edited the question to make the input/output a bit more clear

mluerig
  • 638
  • 10
  • 25
  • 1
    I don't quite understand - can you give an example of what you want th eoutput to look like? – match May 27 '21 at 17:16
  • done. I am mostly trying to make my JSON files more legible to human eyes, as I have some long lists full of raw data, but also meaningful info in shorter lists and dicts – mluerig May 27 '21 at 22:41

1 Answers1

0

The Python json implementation does not let you easily change the behaviour for the builtin Python classes. There is another Stack Overflow question about this than the one you linked : How to change json encoding behaviour for serializable python object?.

But because the file will be re-parsed and re-written later, your preferences about formatting will be lost if the software that does it does not understand your convention. Either you can ensure that the file will not get modified, or find a way to only show this pretty format when it is being displayed to the user, but not in storage. In general, it is better to prettify the file just for the display.

Lenormju
  • 4,078
  • 2
  • 8
  • 22