import json
print('**********Export JSON file**********')
#Dictionary object(dictionary)Generate a
data = dict()
data['message'] = 'Hello, world.'
data['members'] = [
{'name': 'Alice', 'color': '#FA3E05'},
{'name': 'Bob', 'color': '#FFFFAA'}
]
#Get dictionary object as str type and output
print(json.dumps(data, ensure_ascii=False, indent=2))
#Output dictionary object to JSON file
with open('mydata.json', mode='wt', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=2)
print('**********Read JSON file**********')
#Generate a text stream from a JSON file
with open('mydata.json', mode='rt', encoding='utf-8') as file:
print('file: ' + str(file))
#Dictionary object(dictionary)Get
data = json.load(file)
print('data: ' + str(type(data)))
#Output the required part from JSON data
print('message: ' + data['message'])
for member in data['members']:
print(member['name'] + ': ' + member['color'])
The result of running with Python 3.8.2.
**********Export JSON file**********
{
"message": "Hello, world.",
"members": [
{
"name": "Alice",
"color": "#FA3E05"
},
{
"name": "Bob",
"color": "#FFFFAA"
}
]
}
**********Read JSON file**********
file: <_io.TextIOWrapper name='mydata.json' mode='rt' encoding='utf-8'>
data: <class 'dict'>
message: Hello, world.
Alice: #FA3E05
Bob: #FFFFAA
Output JSON file
{
"message": "Hello, world.",
"members": [
{
"name": "Alice",
"color": "#FA3E05"
},
{
"name": "Bob",
"color": "#FFFFAA"
}
]
}
json ---JSON encoders and decoders — Python 3 \ .8 \ .2 documentation
The json API is familiar to users of the standard library marshal and pickle.
Built-in — Python 3 \ .8 \ .2 documentation
Dictionaries can be created by enclosing a comma-separated list of key: value pairs in curly braces. For example: {'jack': 4098,'sjoerd': 4127} or {4098:'jack', 4127:'sjoerd'}. Alternatively, you can create it with the dict constructor.
Recommended Posts