-1

I have this sample json file but Im unable to wor with the keys from my json file.

import json

people_string = """
{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "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;"
    }
}}

"""
x = json.loads(people_string)
#print(x)
#print(type(x))

for a in x["widget"]:
    print(a)

When I run this code i get as output:

debug
window
image
text

How can I access from "window": "title"?

I tried

for a in x['widget']:
    print(a["window"])

but this gives me an error

2
  • 3
    print(x["widget"]["window"]["title"]) Jun 21, 2020 at 21:43
  • thanks dude this worked;) Jun 21, 2020 at 21:52

2 Answers 2

0

After json.loads() it is a nested dictionary.

Nested Dictionary: Nesting Dictionary means putting a dictionary inside another dictionary. Nesting is of great use as the kind of information we can model in programs is expanded greatly.

# Nested dictionary having same keys 
Dict = { 'Dict1': {'name': 'Ali', 'age': '19'}, 

         'Dict2': {'name': 'Bob', 'age': '25'}} 

  
# Prints value corresponding to key 'name' in Dict1 

print(Dict['Dict1']['name']) 


# Prints value corresponding to key 'age' in Dict2 

print(Dict['Dict2']['age']) 
0

After loading the json you can access both keys and values using .items().

Example:

x = json.loads(people_string)

for key, value in x["widget"].items():
    print(key, value)

Output:

debug on
window {'title': 'Sample Konfabulator Widget',
    '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;'
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.