Python JSON Concept
Python JSON Concept
In this tutorial, we'll see how we can create, manipulate, and parse JSON in Python using the
standard a json module. The built-in Python json module provides us with methods and
classes that are used to parse and manipulate JSON in Python.
What is JSON:
JSON (an acronym for JavaScript Object Notation) is a data-interchange format and is most
commonly used for client-server communication
Example:
A JSON is an unordered collection of key and value pairs, resembling Python's native
dictionary.
Keys are unique Strings that cannot be null.
Values can be anything from a String, Boolean, Number, list, or even null.
A JSONO can be represented by a String enclosed within curly braces with keys and
values separated by a colon, and pairs separated by a comma
Example:
# Import the json module.
import json
Example: Convert Python objects into JSON strings, and print the values.
import json
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
Output:
{ "name" : "John" , "age" : 30}
["apple", "bananas"]
["apple", "bananas"]
"hello"
42
31.76
true
false
null
Example: Convert a Python object containing all the legal data types:
import json
x={
"name" : "John",
"age" : 30,
"married" : True,
"divorced" : False,
"children" : ("Ann","Billy"),
"pets" : None,
"cars" : [
{"model" : "BMW 230", "mpg": 27.5},
{"model" : "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
Output: {"name": "John", "age": 30, "married": true, "divorced": false, "children":
["Ann","Billy"], "pets": null, "cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford
Edge", "mpg": 24.1}]}
developer.js
{
"name": "jane doe",
"salary": 9000,
"skills": [
"Raspberry pi",
"Machine Learning",
"Web Development"
],
"email": "[email protected]",
"projects": [
"Python Data Mining",
"Python Data Science"
]
}
developer.py
import json
print("Started Reading JSON file")
with open("developer.json", "r") as read_file:
print("Converting JSON encoded data into Python dictionary")
developer = json.load(read_file)
print("Decoded JSON Data From File")
for key, value in developer.items():
print(key, ":", value)
print("Done reading json file")
Output:
Started Reading JSON file
Converting JSON encoded data into Python dictionary
Decoded JSON Data From File
name : jane doe
salary : 9000
skills : ['Raspberry pi', 'Machine Learning', 'Web Development']
email : [email protected]
projects : ['Python Data Mining', 'Python Data Science']
Done reading json file
39.9086130423918