Skip to content Skip to sidebar Skip to footer

Is It Possible To Skip Outputting Specific Key And Associated Values In Python Json.dumps?

Using json.dumps I have the following output. { '1': { 'fooBar': { '_foo': 'foo', '_bar': 'bar', '_id': '1' }, 'longValueList': [ [

Solution 1:

You can create a temporary copy and remove these keys from it:

from functools import reduce
import operator as op

deftoJSON(self, skip=()):
    obj = self._container.copy()
    for path in skip:
        del reduce(op.getitem, path[:-1], obj)[path[-1]]
    return json.dumps(obj, default=lambda o: o.__dict__,
                      sort_keys=True, indent=4)

Then you can specify the keys as a path:

foo.toJSON(skip=[('1', 'longValueList')])

This also works with list indices:

foo.toJSON(skip=[('1', 'longValueList', 2)])

As a modification you could also use path separators for example (does not work with list indices though):

from functools import reduce
import operator as op

deftoJSON(self, skip=()):
    obj = self._container.copy()
    for path in skip:
        path = path.split('/')
        del reduce(op.getitem, path[:-1], obj)[path[-1]]
    return json.dumps(obj, default=lambda o: o.__dict__,
                      sort_keys=True, indent=4)

foo.toJSON(skip=['1/longValueList'])

Post a Comment for "Is It Possible To Skip Outputting Specific Key And Associated Values In Python Json.dumps?"