3

I have a json like below:

{"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;"
    }
}}

I need to have all the key value pair extracted. e.g. debug=on,title=SampleWidget,name=main_window and so on. How can I do this in generic way? I mean the json can be any other than the one in example but procedure should be the same.

qvpham
  • 1,896
  • 9
  • 17
  • Do you need a dictionary of all couples where the value isn't a dictionary itself? Collapsed dictionary? That wouldn't be a problem? You'd have three `name` keys – Neo Jun 30 '16 at 07:36
  • you will find your answer here: http://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values or here: http://stackoverflow.com/questions/3229419/pretty-printing-nested-dictionaries-in-python – Nevenoe Jun 30 '16 at 07:40

1 Answers1

6
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']
duyue
  • 759
  • 5
  • 12