json.dumps将一个Python数据结构转换为JSON
import json data = { 'name' : 'myname', 'age' : 100, } json_str = json.dumps(data)
方法 | 作用 |
---|---|
json.dumps() | 将python对象编码成Json字符串 |
json.loads() | 将Json字符串解码成python对象 |
json.dump() | 将python中的对象转化成json储存到文件中 |
json.load() | 将文件中的json的格式转化成python对象提取 |
json.dump()和json.dumps()的区别
json参数
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
import json x = {'name':'你猜','age':19,'city':'四川'} #用dumps将python编码成json字符串 y = json.dumps(x) print(y) i = json.dumps(x,separators=(',',':')) print(i) # 输出结果 {"name": "\u4f60\u731c", "age": 19, "city": "\u56db\u5ddd"} {"name":"\u4f60\u731c","age":19,"city":"\u56db\u5ddd"}
json.dumps()用于将python对象转换为json字符串,返回转换后的json字符串
import json #将python对象转换为json字符串 persons = [ { 'username': "zhaoji", "age": "18", "country": "China" }, { "username": "cyj", "age": "18", "country": "China" } ] #调用dumps方法转换python对象 json_str = json.dumps(persons) #打印转换后的json字符串的数据类型 print(type(json_str)) #打印转换后的json字符串 print(json_str)
输出结果为
<class ‘str'>
[{“username”: “zhaoji”, “age”: “18”, “country”: “China”}, {“username”: “cyj”, “age”: “18”, “country”: “China”}]Process finished with exit code 0
json.dump()用于将python对象转换为字符串并且写入文件
import json #将python对象转换为json字符串 persons = [ { 'username': "zhaoji", "age": "18", "country": "China" }, { "username": "cyj", "age": "18", "country": "China" } ] with open("./data/j1.json", "w") as fp: json.dump(persons, fp) fp.close()
写入文件为
[{“username”: “zhaoji”, “age”: “18”, “country”: “China”}, {“username”: “cyj”, “age”: “18”, “country”: “China”}]
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理