[Avg. reading time: 6 minutes]
JSON
JavaScript Object Notation
- Neither row-based nor columnar
- Flexible way to store and share data across systems
- Text-based format using curly braces and key-value pairs
Simplest JSON Example
{"id": "1","name":"Rachel"}
Properties
- Language independent
- Self-describing
- Human-readable
- Widely supported across platforms
Basic Rules
- Curly braces
{}hold objects - Data is represented as key-value pairs
- Entries are separated by commas
- Double quotes are mandatory
- Square brackets
[]hold arrays
JSON Values
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}
Sample JSON Document
{
"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
}
]
}
JSON Best Practices
No Hyphen in your Keys.
{"first-name":"Rachel","last-name":"Green"} is not right. ✘
data.first-name
is parsed as
(data.first) - (name)
Under Scores Okay
{"first_name":"Rachel","last_name":"Green"} is okay ✓
Lowercase Okay
{"firstname":"Rachel","lastname":"Green"} is okay ✓
Camelcase best
{"firstName":"Rachel","lastName":"Green"} is the best. ✓
Use Cases
- APIs and web services
- Configuration files
- NoSQL databases
- Serialization and deserialization
Python Example
Serialize : Convert Python Object to JSON (Shareable) Format. DeSerialize : Convert JSON (Shareable) String to Python Object.
import json
def json_serialize(file_name):
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"}
]
}
json_data=json.dumps(friends_characters,indent=4)
with open(file_name,"w") as f:
json.dump(friends_characters,f,indent=4)
def json_deserialize(file_name):
with open(file_name,"r") as f:
data=json.load(f)
print(data,type(data))
def main():
file_name="friends_characters.json"
json_serialize(file_name)
json_deserialize(file_name)
if __name__=="__main__":
main()