[英]Python extract only 'key' values in in nested JSON where 'value' is a dictionary in a list
[英]Python extract all key values in in nested JSON in a list
我有一個像下面的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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.