JSON
{"id": "1","name":"Rachel"}Properties
Basic Rules
JSON Values
Sample JSON Document
JSON Best Practices
Use Cases:
Serialize
Last updated
{"id": "1","name":"Rachel"}Last updated
String {"name":"Rachel"}
Number {"id":101}
Boolean {"result":true, "status":false} (lowercase)
Object {
"character":{"fname":"Rachel","lname":"Green"}
}
Array {
"characters":["Rachel","Ross","Joey","Chanlder"]
}
NULL {"id":null}{
"characters": [
{
"id" : 1,
"fName":"Rachel",
"lName":"Green",
"status":true
},
{
"id" : 2,
"fName":"Ross",
"lName":"Geller",
"status":true
},
{
"id" : 3,
"fName":"Chandler",
"lName":"Bing",
"status":true
},
{
"id" : 4,
"fName":"Phebe",
"lName":"Buffay",
"status":false
}
]
}{"first-name":"Rachel","last-name":"Green"} is not right. ✘{"first_name":"Rachel","last_name":"Green"} is okay ✓{"firstname":"Rachel","lastname":"Green"} is okay ✓{"firstName":"Rachel","lastName":"Green"} is the best. ✓import json
# Python dictionary with Friend's characters
friends_characters = {
"characters": [
{"name": "Rachel Green", "job": "Fashion Executive"},
{"name": "Ross Geller", "job": "Paleontologist"},
{"name": "Monica Geller", "job": "Chef"},
{"name": "Chandler Bing", "job": "Statistical Analysis and Data Reconfiguration"},
{"name": "Joey Tribbiani", "job": "Actor"},
{"name": "Phoebe Buffay", "job": "Massage Therapist"}
]
}
print(type(friends_characters), friends_characters)
print("-" * 200 )
# Serializing json
json_data = json.dumps(friends_characters, indent=4)
print(type(json_data), json_data)
# Saving to a file
with open('friends_characters.json', 'w') as file:
json.dump(friends_characters, file, indent=4)import json
# JSON string with Friend's characters
json_data = '''
{
"characters": [
{"name": "Rachel Green", "job": "Fashion Executive"},
{"name": "Ross Geller", "job": "Paleontologist"},
{"name": "Monica Geller", "job": "Chef"},
{"name": "Chandler Bing", "job": "Statistical Analysis and Data Reconfiguration"},
{"name": "Joey Tribbiani", "job": "Actor"},
{"name": "Phoebe Buffay", "job": "Massage Therapist"}
]
}
'''
# Parsing JSON to dictionary
friends_characters = json.loads(json_data)
print(friends_characters, type(friends_characters))
## Alternate way to read from file
# Path to your JSON file
file_path = 'friends_characters.json'
# Open the file and read the JSON content
with open(file_path, 'r') as file:
data = json.load(file)
print(data, type(data))