JSON (JavaScript Object Notation) is a way of expressing information. JSON is usually easy to understand. It can express information like XML. It is based on JavaScript's notation for object literals. However, JSON is stricter.
JSON and XML are both often used in AJAX. Even though JSON is named after JavaScript, it can be used in other programming languages, such as Python (PHP, etc.)
This is an example of JSON:
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
"phoneNumber":
[
{
"type" : "",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
}
JSON Encoding and Decoding in Python
Encoding:
import json
sampleDict = {
"firstName": "John",
"lastName" : "Smith"
}
sampleJson = json.dumps(sampleDict, indent=4)
Decoding:
import json
# A JSON string or can be a JSON response
sampleJson = """{ "firstName": "John", "lastName" : "Smith"}"""
sampleDict = json.loads(sampleJson)
print(sampleDict['firstName'])
print(sampleDict['lastName'])