[Python](EN) Parsing JSON file in Python
Read JSON file and parse it to dictionary type data in python
Environment and Prerequisite
- Python(3.X)
Parse json file using with statement and json module
- Easily parse json file contents to dictionary by using
with
statement andjson
module
import json # import json module
# with statement
with open('json file path or name') as json_file:
json_data = json.load(json_file)
...
Examples
example.json
{
"json_string": "string_example",
"json_number": 100,
"json_array": [1, 2, 3, 4, 5],
"json_object": { "name":"John", "age":30},
"json_bool": true
}
example.py
import json
# open file using with statement
# assume json file is in same directory
with open('example.json') as json_file:
json_data = json.load(json_file)
# String
# Get string type data
# Key is json_string
json_string = json_data["json_string"]
print(json_string)
# Numeric
# Get numeric type data
# Key is json_number
json_number = json_data["json_number"]
print(str(json_number)) # 숫자이기 때문에 str()함수를 이용
# Array
# Get array type data
# Key is json_array
json_array = json_data["json_array"]
print(json_array)
# Ojbect
# Get object type data
# Key is json_object
# Default type is dictionary
# You need to serialize it if you need python object (additional code needed)
json_object = json_data["json_object"]
print(json_object)
# Bool
# Get bool type data
# Key is json_bool
json_bool = json_data["json_bool"]
print(json_bool)