知行编程网知行编程网  2022-12-30 21:00 知行编程网 隐藏边栏  1 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python之JSON函数介绍的相关知识,包括python input函数,以及python format函数这些编程知识,希望对大家有参考作用。


Python的JSON函数介绍


JSON函数

使用 JSON 函数需要导入 json 库:import json。

Python的JSON函数介绍

举例说明,如下:

a.json内容格式:

{"car":{"price":1100,"color":"red"},"mac":{"price":7999,"color":"black"},"abc":{"price":122,"color":"green"}}


json.load()

import json
with open('a.json') as fp:
    shop_dic = json.load(fp)  #从a.json文件内读取数据,返回结果为字典:{'abc': {'price': 122, 'color': 'green'},
     'mac': {'price': 7999, 'color': 'black'}, 'car': {'price': 1100, 'color': 'red'}}
    print(shop_dic)


json.loads()

s_json = '{"name":"niuniu","age":20,"status":true}'
print(json.loads(s_json))         #将json串转换为字典:{'age': 20, 'status': True, 'name': 'niuniu'}


json.dump()

import json
with open('a.json', 'a+') as fp:
    dic = {'name': 'niuniu', 'age': 18}
    fp.seek(0)
    fp.truncate()
    json.dump(dic, fp)    #将字典转换为json串写入文件

写入的a.json如下:

{"age": 18, "name": "niuniu"}
json.dumps()
import json
dic = {'name': 'niuniu', 'age': 18}
print(json.dumps(dic))           #将字典转换为json串:{"name": "niuniu", "age"


扩展小知识点:

将字典内容写入json文件,包含中文。

1. 中文写入json文件后显示乱码,怎么解决? ensure_ascii = False

2.手写词典内容显示为漏行,显示不美观。如何解决?缩进 = 4

import json
d = {"Name": "战神","sex" : ["男","女","人妖"],"Education":{"GradeSchool" : "第一小学",
"MiddleSchool" : ["第一初中" , "第一高中"], "University" :{ "Name" : "哈佛大学", "Specialty" : ["一年级","二年级"]}}}
with open('a.json', 'w', encoding='utf-8') as f:
    # 中文显示乱码问题, ensure_ascii = False
    # json格式化问题, indent = 8
    # s = json.dumps(d, ensure_ascii=False, indent=8)  字典转换为json 字符串
    # f.write(s)
    
    #第二种写法
    json.dump(d, f, ensure_ascii=False,indent=8)

写入的json文件,a.json:

Python的JSON函数介绍

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享