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