python json 模块

json模块共用四个方法

json.dumps : dict转成str     json.dump是将python数据保存成json

json.loads:str转成dict          json.load是读取json数据 

具体用法

   import json
with open('product.json', encoding='utf-8') as fr, open('.product', 'w', encoding='utf-8') as fw:
        fr.seek(0)
        product=json.load(fr)
        product[name]={  'color':color,
                         'money':price,
                         'count':count
                         }
        fr.close()
        json.dump(product,fw,indent=4,ensure_ascii=False)
import json

user_info = '''
    {"小明":"123456","小红":"456789"}
'''
 user_dic = json.loads(user_info)  #把json传(字符串)转成字典
 print(user_dic)

stu_info  = { 'laowang':{ 'cars':['BMW','Ben-z'] }  }
stu_str = json.dumps(stu_info) #把字典转成json(字符串)
print('json....',type(stu_str)

注意:

如果文件是空的,是用json.load 方法是会把报错的,必须提前在文件中写一个json串

本文为个人的实际操作经验之谈,转载、复制请注明出处,谢谢!
原文地址:https://www.cnblogs.com/zhouxudong/p/9198696.html