python中json.dump()与json.dumps()的区别

1.将python数据结构转换为json字符串(json.dumps())

>>> import json
>>> data={‘name‘:‘pipi‘,‘age‘:18}
>>> json.dumps(data)
‘{"name": "pipi", "age": 18}‘

2.将json格式的字符串转换为python数据结构(json.loads())

>>> json_str=‘{"name": "pipi", "age": 18}‘
>>> json.loads(json_str)
{‘name‘: ‘pipi‘, ‘age‘: 18}

 3.将json对象写入文件中(json.dump())

data={‘name‘:‘pipi‘,‘age‘:18}
>>> with open("c:/Users/cale/json.txt",‘w‘) as f:
    json.dump(data,f)

python中json.dump()与json.dumps()的区别

 4.从文件中获取json对象

with open("c:/Users/cale/json.txt",‘r‘) as f:
    data=json.load(f)

    
>>> data
{‘name‘: ‘pipi‘, ‘age‘: 18}
>>>

注:如果用f.read()获取的是一个字符串,而不是json对象

with open("c:/Users/cale/json.txt",‘r‘) as f:
    data=f.read()

    
>>> data
‘{"name": "pipi", "age": 18}‘

相关推荐