当前位置: 首页 > news >正文

【python】JSON数据类型与Python数据类型之间的转化

注:最后有面试挑战,看看自己掌握了吗


🌸I could be bounded in a nutshell and count myself a king of infinite space.
 特别鸣谢:木芯工作室
特别鸣谢:木芯工作室 、Ivan from Russia


JSON格式文件

上文看出,没有经过格式化处理的文本非常垃圾,必须得有个格式!
别人如果想要通过程序自动读取该文件信息,也非常难受
JSON就是来解决这个问题的 弥撒亚
Messiah

JSON格式

JavaScript Object Notation ---------JavaScript对象标注符号

序列化与反序列化

序列化:把python数据转换为JSON格式
反序列化:反过来

作用

序列化后的JSON格式字符串可以存储在文件或数据中,也能通过网络连接传送到远程的机器

JSON常用数据结构

键值对的集合

在不同语言被理解为不同的东西
可能是 对象,记录, 结构, 字典, 哈希表, 有序列表, 关联数组

值的有序列表

大部分语言中 被理解为数组

python种 主要对应列表元组

JSON数据类型与Python数据类型之间的转化

python自带处理JSON数据的模块
该模块的dumps实现python数据转为JSON数据
loads实现JSON数据转为python数据的过程

JSON格式和python的区别

json的对象格式在开始和结尾加了单引号,因为所有json数据都是以字符串形式表示的

dumps
loads

# coding=gbkimport json
p_d = {'tt':20,'eq':95,'cc':52}
print(p_d)
p_2_j = json.dumps(p_d)# dumps把字典转为json数据
print(p_2_j)# JSON格式和python的区别:json的对象格式在开始和结尾加了单引号,因为所有json数据都是以字符串形式表示的j_2_p = json.loads(p_2_j)
print(j_2_p){'tt': 20, 'eq': 95, 'cc': 52}
{"tt": 20, "eq": 95, "cc": 52}
{'tt': 20, 'eq': 95, 'cc': 52}

读写json文件

python的json模块为json提供了dumpload操作对象

dump 把python 写到json文件

def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,allow_nan=True, cls=None, indent=None, separators=None,default=None, sort_keys=False, **kw):

obj–python语言对象
f-------以字符串知名存储的文件名,可以带路径
ensure_ascii—表示只接受ascii表数据类型, 当为false时候接受其他 如中文

Serialize obj as a JSON formatted stream to fp (a
.write()-supporting file-like object).
将“ obj”序列化为 JSON 格式的流到“ fp”(a”. write ()“-支持类似文件的对象)。

If skipkeys is true then dict keys that are not basic types
(str, int, float, bool, None) will be skipped
instead of raising a TypeError.
如果“ skipkeys”为真,那么“ dict”键不是基本类型(“ str”、“ int”、“ float”、“ bool”、“ None”)将被跳过而不是引发“ TypeError”。

If ensure_ascii is false, then the strings written to fp can
contain non-ASCII characters if they appear in strings contained in
obj. Otherwise, all such characters are escaped in JSON strings.
如果“ sure _ ascii”为 false,则写入“ fp”的字符串可以中包含的字符串中出现的非 ASCII 字符否则,所有这些字符将在 JSON 字符串中转义。

load 把json写到 python数据类型

def load(fp, *, cls=None, object_hook=None, parse_float=None,parse_int=None, parse_constant=None,object_pairs_hook=None, **kw):

Deserialize fp (a .read()-supporting file-like object containing
a JSON document) to a Python object.

读写JSON文件基本案例

# coding=gbkimport json
import sys
def saveTOJSON(filename,dicObject):flag = Falseif type(dicObject)!=dict:return flagtry:j_file = open(filename,'w')json.dump(dicObject,j_file,ensure_ascii=False)flag = Trueexcept:print('个%s这'%(filename))finally:if flag:j_file.close()return flagdef GetFromJSON(filename):flag = FalsedicObject = {}try:j_file = open(filename,'r')dicObject=json.load(j_file)flag = Trueexcept:print("duqu%schucuo"%(filename))finally:if flag:j_file.close()return dicObjectstudents = {'mingzi':"xiaoming",'tt':"20",'eq':95,'cc':52}
filename='student.json'
f_OK = saveTOJSON(filename,students)
if f_OK:print("baocun chenggong")
else:sys.exit()d_get_s=GetFromJSON(filename)
if d_get_s:print(d_get_s)# 打印返回的字典对象
# coding=gbk
import json
import sys
def saveTOJSON(filename,dicObject):flag = Falsetry:j_file = open(filename,'w')json.dump(dicObject,j_file,ensure_ascii=False)flag = Trueexcept:print('个%s这'%(filename))finally:if flag:j_file.close()return flagdef GetFromJSON(filename):flag = FalsedicObject = {}try:j_file = open(filename,'r')dicObject=json.load(j_file)flag = Trueexcept:print("duqu%schucuo"%(filename))finally:if flag:j_file.close()return dicObjectstudents = 'xiaomingadsfasfsadf'
filename='student.json'
f_OK = saveTOJSON(filename,students)
if f_OK:print("baocun chenggong")
else:sys.exit()d_get_s=GetFromJSON(filename)
if d_get_s:print(d_get_s)# 打印返回的字典对象
http://www.lryc.cn/news/28434.html

相关文章:

  • Spring——什么是事务?传播行为?事务隔离级别有哪些?
  • 【项目实战】使用Feign服务间相互调用,其实OpenFeign也没有想象中那么难嘛
  • tun驱动之ioctl
  • [acwing周赛复盘] 第 93 场周赛20230304
  • NOIP2022 T4 比赛
  • 计算机组成原理
  • 1. 命名规范
  • 论文投稿指南——中文核心期刊推荐(新闻事业)
  • 【Linux】工具(4)——make/Makefile
  • 【企业服务器LNMP环境搭建】nginx安装
  • Linux 配置规范 操作系统 _S3A3G3
  • 基于信息间隙决策理论的碳捕集电厂调度(Matlab代码实现)
  • 【C语言进阶:指针的进阶】回调函数
  • C++模板的使用
  • 三天Golang快速入门—面向对象
  • 开发手册——一、编程规约_6.并发处理
  • ACM---大一第三周周赛(Floyd算法+并查集算法学习周)
  • spring整合mybatis和Junit
  • Spring Boot 3.0系列【7】核心特性篇之JSON
  • 【数据结构初阶】二叉树顺序结构:堆的实现
  • C/C++:动态内存管理
  • 黑猫带你学eMMC协议第28篇:eMMC的开漏和推挽模式(push-pull open drain)
  • simulink PID控制
  • 如何在for循环内执行异步操作
  • 性能测试——LoadRunner: Controller的使用
  • ChatGPT解答:纯前端文档预览,Vue实现,无需后端,支持Word、Excel、PPT、pdf、文本、图片,附接入demo和文档
  • 刷题记录:牛客NC13950 Alliances 到树上联通点集的最短距离
  • 行为型模式 - 状态模式State
  • 电视剧《狂飙》太过诡异,主演各个悄无声息,龙套演员却身价倍增
  • 【微信小程序】-- 案例 - 本地生活(二十)