第四节之json操作 和字典的操作与文件操作结合

使用方法 需要导入json模块 为什么用json 

json是一个字符串  、所有语言都能解析     存数据存json和字典之间互相转行是比较方便的

import json
d = {'name':'xiaohei','cars':[1,2,3],'house':(4,5,6),
'addr':'北京','age':18,'sex':'男','money':100,'msg':'ok'}
#json就是一个字符串,只不过是所有语言都能解析这个字符串

result = json.dumps(d,ensure_ascii=False,indent=4) #pyton的数据类型转json的 #(list、tuple、dict)这三种类型类型都可以转字符串,子典写法单引号,没有双引号
print(result)
print(type(result))

将json转成字典操作
json_str = ' {"name": "xiaohei", "cars": [1, 2, 3], "house": [4, 5, 6]} '
dict2 = json.loads(json_str)


 

文件里面只能写字符串 存到数据库 

如果你想把字典写进文件里面写不了 ,因为只能写字符串 

需要先转成json 在写进文件,因为json串本来就是字符串 

或者把字符串转成json 在转成字典  、

不用想以前自己在处理 分割  取key和value  

一共两种方法  字典转成字符串 

import json
d = {'name':'xiaohei','cars':[1,2,3],'house':(4,5,6),
'addr':'北京','age':18,'sex':'男','money':100,'msg':'ok'}
#json就是一个字符串,只不过是所有语言都能解析这个字符串

result = json.dumps(d,ensure_ascii=False,indent=4) #pyton的数据类型转json的 #(list、tuple、dict)这三种类型都可以
# print(result)
print(type(result))

字符串 转成字典 

import json
json_str = ' {"name": "xiaohei", "cars": [1, 2, 3], "house": [4, 5, 6]} '
dict2 = json.loads(json_str)

print(type(dict2))

还有两个方法 load和dump 这种就是为了读文件的操作帮你简化乐读文件的操作


#content = f.read()

#d = json.loads(content)

#d = json.load(f) #帮你封装了处理文件的功能 简化了#content = f.read()这步骤操作    读文件

这一行代码相当于上面两行代码  

写的操作 

#json_str = json.dumps(d,indent=4,ensure_ascii=False)
#f.write(json_str)

#json.dump(d,f,indent=4,ensure_ascii=False) 节省代码,省了上面两个步骤 写文件 

hzy = [1,2,3,4]
with open('info2.json','w',encoding='utf-8') as fw:      写的操作 
json.dump(hzy,fw,ensure_ascii=False,indent=4)
 
# with open('info.txt',encoding='utf-8') as fw:           读的操作 
# d = json.load(fw)
# print(d)
# print(d.get('name'))
# print(d.get('money'))

字典的操作 

字典的增删改查 

字典的增加 a={}

a[ces]=name

a.setdefaul t两种方法   区别不一样第一种会覆盖,第二种不会覆盖    已经存在的不能赋值  

删除 del   clerar()   第二种清除所有    pop  删除key不存咋都会报错

字典的修改   a[ces]=cess  

字典的查询 a.get('ces') 找不到返回一个none        a[ces]

字典的更新 d.update(a=1)更新一个key 

a=

字典的实战

# 本周作业:
# 写一个管理商品的程序,商品文件格式在a.json里面
# 提供商品的增删改查功能
# choice = input('请输入你的选择:1、查看商品 2、新增商品 3、修改商品 4、删除商品')
# #1、查看商品,输入商品名称,print单个商品的信息,价格、数量,输入all,查看所有商品
# #2、新增商品,输入商品名称、数量、价格,数量是大于0的整数,价格必须是大于0的数值,
# #如果商品存在,无法添加
# #3、修改商品,输入商品名称、数量、价格,商品存在才可以修改 数量是大于0的整数,价格必须是大于0的数值,
# #4、输入商品名称,如果存在,删除
#说白了就是对字典的增删改查,json转成字典
import json
ces='a.json'#常量
def is_digit(number):
s = str(number)
if s.isdigit():
if int(s) > 0:
return True

def is_price(price): #>0的整数和小数都可以 #1.7
s = str(price)
if is_digit(s):
return True
else:
if s.count('.') == 1: # 1.3
left, right = s.split('.')
if left.isdigit() and right.isdigit(): # 正小数 #0.0
if float(s)>0:
return True
def read():
with open(ces, encoding='utf-8')as fr:#读文件的操作
return json.load(fr)
def write(data):
with open(ces,'w',encoding='utf-8')as fw:#写文件你传进来是一个字典,写进json 需要转换下
return json.dump(data,fw,ensure_ascii=False,indent=4)
def reads(): #查看
reading=read()
name=input('输入商品名称').strip()
if not name:
print('不允许为空')
elif name =='all':
print(read())
elif name not in reading:
print('商品不存在')
else:
named=reading.get(name)
print('商品信息',named)
def add():#商品增加
names=input('输入商品名称').strip()
price = input('输入商品价格').strip()
count=input('输入商品数量').strip()
if names and price and count:
if is_price(price) and is_digit(count):
product=read()
if names not in product:
product[names]={"count": count,"price": price}
write(product)
print('新增商品成功')
else:
print('商品已经存在')
else:
print('价格/数量不合法')
else:
print('不允许输入为空')
def xiugai():
names = input('输入商品名称').strip()
new=input('输入新的商品名称').strip()
price = input('输入商品价格').strip()
count = input('输入商品数量').strip()
if names and price and count:
if is_price(price) and is_digit(count):
product = read()
if names in product or new in product:
product.pop(names)#删除原来的
product[new] = {"count": count, "price": price}
write(product)
print('修改商品成功')
else:
print('商品不存在')
else:
print('价格/数量不合法')
else:
print('不允许输入为空')
def delete():
name=input('输入商品').strip()
if name:
product=read()
if name not in product:
print('商品不存在')
else:
product.pop(name)
write(product)
print('删除成功')
else:
print('不允许输入为空')
choice = input('请输入你的选择:1、查看商品 2、新增商品 3、修改商品 4、删除商品')
#这里可以写成两种一种直接让choice===几打印那个函数
# 另一种搞成字典
funps={'1':reads,'2':add,'3':xiugai,'4':delete}
if choice in funps:
funps[choice]()
else:
print('输入正确的选择')
原文地址:https://www.cnblogs.com/weilemeizi/p/14019189.html