Shenglian / -WORK_TIP

工作上小技巧
4 stars 1 forks source link

[python] Reading and Writing JSON to a File #171

Open Shenglian opened 5 years ago

Shenglian commented 5 years ago
# Write

import json
data = {}

data['person'] = []

data['person'].append({
 'name': 'Sheng',
 'age': 20,
 'sex': male
})

data['person'].append({
 'name': 'Cai',
 'age': 18,
 'sex': female
})

with open('person.json', 'w') as outfile:
 json.dump(data, outfile)

# Read
import json 

with open('person.json') as json_file:
 data = json.load(json_file)
 for p in data['person']:
 print('Name: ', + p['name'])
 print('Age: ', + str(p['age']))
 print('Sex: ', + p['sex'])
 print('  ')