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串

posted on 2018-06-19 15:15  小狐狸记录测试点点滴滴  阅读(135)  评论(0编辑  收藏  举报