import json
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
a= json.dumps(prices) #编码为json
print(a)
'''
Out[40]: '{"ACME": 45.23, "AAPL": 612.78, "IBM": 205.55, "HPQ": 37.2, "FB": 10.75}'
'''
b = json.loads(a) #解码为python对象
print(b)
'''
Out[42]: {'AAPL': 612.78, 'ACME': 45.23, 'FB': 10.75, 'HPQ': 37.2, 'IBM': 205.55}
'''
import json
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
with open('price.json', 'w') as f:
json.dump(prices,f)
此时在当前目录下生成prices.json文件,内容如下:。
{"ACME": 45.23, "AAPL": 612.78, "IBM": 205.55, "HPQ": 37.2, "FB": 10.75}
import json
with open('price.json', 'r') as f:
a = json.load(f) #此时a是一个字典对象
print(a['ACME'])
'''
输出结果:45.23
'''