Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Create Python Dictionary from JSON Input



You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content

{
   "id": "file",
   "value": "File",
   "popup": {
      "menuitem": [
         {"value": "New", "onclick": "CreateNewDoc()"},
         {"value": "Open", "onclick": "OpenDoc()"},
         {"value": "Close", "onclick": "CloseDoc()"}
      ]
   }
}

You can load it in your python program and loop over its keys in the following way:

import json
f = open('data.json')
data = json.load(f)
f.close()

# Now you can use data as a normal dict:

for (k, v) in data.items():
print("Key: " + k)
print("Value: " + str(v))

This will give the output:

Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
Updated on: 2020-06-17T11:22:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements