Python JSON Parsing
In this tutorial you will learn:
- JSON
- JSON parsing in Python
- Converting to JSON
JSON
JSON simply means Javascript Object Notation. It’s a standard format for exchanging data. It provides a simple way to organize information in easily readable format. JSON is important in Python because Python can also handle backend and front end web development tasks. An excellent library used for web development tasks in Python is called django.
myJson = '{"Test": 1, "First Name": "Python", "Last Name": "Programming", "numbers": [1334, 445]}'
JSON parsing in Python
To do JSON parsing in Python we first need to import json module which has a lot of helper functions that can help us in parsing the JSON. This most important function is the loads function which converts the JSON in the form of a Dictionary object which can be easily handled in Python.
Example:
- import json
- print("** JSON Parsing **")
- myJson = '{"Test": 1, "First Name": "Python", "Last Name": "Programming", "numbers": [1334, 445]}'
- parsed = json.loads(myJson)
- print(parsed["First Name"])
- print(parsed["Last Name"])
- print(parsed["numbers"][1])
In this example the loads functions gives us the result in Dictionary form which is saved in parsed variable and printed using print commands.
- employee = '{"empName": "Mike", "age": 60, "skills": ["Python", "C++", "C#"], "kids": {"john": { "age": 30, "occupation": "Banker"}, "Tom": {"age": 25, "occupation": "Engineer"}}}'
- emp = json.loads(employee)
- print( emp["empName"])
- print( emp["age"])
- print(emp["kids"]["Tom"]["occupation"])
In this example we parsed a nested json using the loads function and we can note that for three levels of nesting we used 3 sets of square brackets to reach the required value.
Converting to JSON
Just like loads function allows us to convert a JSON to a Dictionary similarly there is another function in json module called dumps which allows us to convert Dictionary object to JSON.
Example:
- emp = {
- "empAge": 55,
- "salary": 494,
- "deparment": "IT",
- "empName": "Mike",
- }
- js = json.dumps(emp)
- print("Json is:", js)
Here we can see that how easy it is to convert Python Dictionary object to json by simply passing it to the json.dumps function.
Add new comment
- 331 views