import json

注:
json 串里面只有双引号,没有单引号
bejson.com 在线检验json 的格式是否正确

 

##json 串是一个字符串

将文件中包含字典的字符串转为字典,方法:
f = open('product.json',encoding = 'utf-8')
res = f.read()
product_dic = json.loads(res) #把 json 串,变成python的数据类型

print(type(product_dic))
print(product_dic.get('product_info')) #获取 k = 'product_info'的 value 值

 

##json.load()等功能(无需先读文件)

json.load(f) #传一个文件对象,它会帮你读文件

等同:
res = f.read()
product_dic = json.loads(res)

 

##json.dumps(d) #将字典转换成json,即字典转换成字符串

json.dumps(d,ensure_ascii=False,indent=4)
字典 解决中文乱码 缩进

例:
b = {'username':
    {'xiaolin':'女'},
  'telphone':
    {'移动':172763748}
}
f = open('xinxi.json','w',encoding='utf-8')
w = json.dump(b,ensure_ascii=False,indent=4)
f.write(w)

 

##json.dump(d,fw) #操作文件

例:
b = {'username':
    {'xiaolin':'女'},
  'telphone':
    {'移动':172763748}
}
f = open('xinxi.json','w',encoding='utf-8')
w = json.dump(b,f,ensure_ascii=False,indent=4) #直接写到文件中

 

##封装一个读 / 写 json 文件函数##

import json
def op_data(filename,dic=None):
  if dic:
    with open(filename,'w',encoding = 'utf-8') as fw:
    json.dump(dic,fw,ensure_ascii=False,indent = 4)
  else:
    with open(filename,encoding = 'utf-8') as fr:
    return json.load(fr)