Search code examples
pythonjsonpretty-print

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": [
        [
            1,
            2,
            ...
            n,

        ],
...

The above output is generated using this class object function.

def toJSON(self):
    return json.dumps(self._container, default=lambda o: o.__dict__,
                      sort_keys=True, indent=4)

The key longValueList is associated with really long value list and I do not need it printed when doing these specific json prints. How can prevent pythons json.dumps from printing the key and values? Looking at the documentation for python json.dumps I could not see any options in the constructor that skip specific keys by name when calling json.dumps


Solution

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

    from functools import reduce
    import operator as op
    
    def toJSON(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
    
    def toJSON(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'])