是否可以跳过在python json.dumps中输出特定的键和关联值?

时间:2019-03-13 21:39:55

标签: python json pretty-print

使用json.dumps,我有以下输出。

{
"1": {
    "fooBar": {
        "_foo": "foo",
        "_bar": "bar",
        "_id": "1"

    },
    "longValueList": [
        [
            1,
            2,
            ...
            n,

        ],
...

以上输出是使用此类对象函数生成的。

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

longValueList与很长的值列表相关联,在执行这些特定的json打印时,我不需要将其打印出来。如何防止pythons json.dumps打印键和值?查看python json.dumps的文档,我在构造函数中看不到任何在调用json.dumps

时按名称跳过特定键的选项。

1 个答案:

答案 0 :(得分:0)

您可以创建一个临时副本并从中删除以下密钥:

MyApp

然后您可以将键指定为路径:

Dim xmlDoc As New MSXML2.DOMDocument
Dim countries As MSXML2.IXMLDOMNodeList, country As MSXML2.IXMLDOMNode

'need these next two....
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.setProperty "SelectionNamespaces", "xmlns:wb='http://www.worldbank.org'"

'loading from a local file for testing
If Not xmlDoc.Load(ThisWorkbook.Path & "\country.xml") Then
    MsgBox ("Blad ladowania URL")
    Exit Sub
End If

Set countries = xmlDoc.SelectNodes("//wb:country")

Debug.Print countries.Length

For Each country In countries
    Debug.Print "------------------------------------"
    Debug.Print "id", country.Attributes.getNamedItem("id").Text
    Debug.Print "Name", country.SelectSingleNode("wb:name").nodeTypedValue
    Debug.Print "Region", country.SelectSingleNode("wb:region").nodeTypedValue
    'etc
Next country

这也适用于列表索引:

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)

作为修改,您还可以使用路径分隔符,例如(虽然不适用于列表索引):

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