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

2021-02-14 19:23

阅读:553

标签:数据   获取   文件中   user   image   json对象   区别   pen   字符串转换   

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)

技术图片

 

 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}

 

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

标签:数据   获取   文件中   user   image   json对象   区别   pen   字符串转换   

原文地址:https://www.cnblogs.com/pipile/p/12718760.html


评论


亲,登录后才可以留言!