1import json
2
3data = {}
4data['people'] = []
5data['people'].append({
6 'name': 'Scott',
7 'website': 'stackabuse.com',
8 'from': 'Nebraska'
9})
10data['people'].append({
11 'name': 'Larry',
12 'website': 'google.com',
13 'from': 'Michigan'
14})
15data['people'].append({
16 'name': 'Tim',
17 'website': 'apple.com',
18 'from': 'Alabama'
19})
20
21with open('data.txt', 'w') as outfile:
22 json.dump(data, outfile)
23
1import json
2
3with open('data.txt') as json_file:
4 data = json.load(json_file)
5 for p in data['people']:
6 print('Name: ' + p['name'])
7 print('Website: ' + p['website'])
8 print('From: ' + p['from'])
9 print('')
10
1>>> import json
2>>> data = {'item': 'Beer', 'cost':'£4.00'}
3>>> jstr = json.dumps(data, indent=4)
4>>> print(jstr)
5{
6 "item": "Beer",
7 "cost": "\u00a34.00"
8}
9
1>>> jstr = json.dumps(data, ensure_ascii=False, indent=4)
2>>> print(jstr)
3{
4 "item": "Beer",
5 "cost": "£4.00"
6}
7
1>>> import json
2>>> data = {'people':[{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
3>>> json.dumps(data, indent=4)
4{
5 "people": [
6 {
7 "website": "stackabuse.com",
8 "from": "Nebraska",
9 "name": "Scott"
10 }
11 ]
12}
13