Python json
JSON introduction
- JSON - JavaScript Object Notation
- The most popular format for data exchange
- Read below external articles to know more about JSON
JSON v/s Python
- JSON format is similar to dict notation in Python
- Fields are always enclosed only by double quote
"
character - Instead of
True
there is true
(lowercase) - Instead of
False
there is false
(lowercase) - Instead of
None
there is null
list
is known as array
(despite the same syntax) dict
is known as object
(despite the same syntax) - There is no
tuple
or set
- Coma
,
is not allowed after the last element in list
or object
camelCase
is convention, although snake_case
is also valid
convert JSON string to python dictionary
- use
json.loads(json_string)
to convert string to python dict. - lets see an example
import json
data_str = '{"name":"Apple", "cost": 30}'
data = json.loads(data_str)
print(type(data))
# output: <class 'dict'>
print(data["name"])
# output: Apple
convert python objects to JSON string
- use
json.dumps(obj)
to convert python object to JSON string - let's look at an example
import json
students = ["Anji", "David", "Paul"]
data_str = json.dumps(students)
print(type(data_str))
# output: <class 'str'>
print(data_str)
# output: ["Anji", "David", "Paul"]
write JSON to file - json.dump
- use
json.dump(data, file)
to write the data to file. - let's look at an example
import json
data = {"students": ["Travis", "Sudhakar", "Devika"]}
file_path = "/tmp/data.json"
with open(file_path, "a+") as _file:
json.dump(data, _file)
- open the file and we can find
{"students": ["Travis", "Sudhakar", "Devika"]}
as the text content.
load JSON data from file to memory - json.load
- use
json.load()
to load data from file to memory - let's look at the below code
import json
data = None
with open(file_path, "r") as _file:
data = json.load(_file)
print(data)
# output: {'students': ['Travis', 'Sudhakar', 'Devika']}
Reference: