Is it possible to skip outputting specific key and associated values in python json.dumps?

試著忘記壹切 提交于 2020-01-06 10:22:25

问题


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


回答1:


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'])


来源:https://stackoverflow.com/questions/55151617/is-it-possible-to-skip-outputting-specific-key-and-associated-values-in-python-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!