Python 提取列表中嵌套 JSON 中的所有键值

标签 python json

我有一个如下所示的 json:

{"widget": {
    "debug": "on",
    "window": {
        "title": "SampleWidget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}

我需要提取所有键值对。例如debug=on,title=SampleWidget,name=main_window 等等。 我怎样才能以通用方式做到这一点?我的意思是 json 可以是示例中的 json,但过程应该相同。

最佳答案

data = {"widget": { "debug": "on", "window": { "title": "SampleWidget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } }} 

def pairs(d):
    for k, v in d.items():
        if isinstance(v, dict):
            yield from pairs(v)
        else:
            yield '{}={}'.format(k, v)

print(list(pairs(data)))
$ python3.5 extract.py 
['size=36', 'alignment=center', 'data=Click Here', 'onMouseUp=sun1.opacity = (sun1.opacity / 100) * 90;', 'vOffset=100', 'name=text1', 'hOffset=250', 'style=bold', 'name=sun1', 'hOffset=250', 'vOffset=250', 'alignment=center', 'src=Images/Sun.png', 'debug=on', 'name=main_window', 'title=SampleWidget', 'width=500', 'height=500']

关于Python 提取列表中嵌套 JSON 中的所有键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38116546/

相关文章:

json - 如何从 Auto Scaling 组获取私有(private) IP 地址

javascript - 从源 'http://github/..file.json' 访问位于 'null' 的 XMLHttpRequest 已被 CORS 策略 : 阻止

python - 在 Pytorch 中对张量 [batch, channel, sequence, H,W] 运行 conv2d

python - 为什么 SIFT 不适用于 OpenCV 中使用 Python 的 8 位图像 (JPEG)?

python - 在 OOP Python tkinter 中的多个类中使用具有相同参数的一个函数的最佳方法是什么

javascript - 将一些数据转换成 json 格式但不确定它是否有效

java - 使用 Jackson 合并两个 JSON 文档

python - 如何在 python 中创建图形列表?

python - Zapier 操作代码 : Python will not run with input_data variable

c - 是否可以在编程语言 C 中仅解析一个 JSON 键/字段/属性