笔记-python-standard library-19.2 json
笔记-python-standard library-19.2 json
1. JSON简介
JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
2. 安装使用
使用json函数需导入json库:import json
python3环境自带该库
source code: Lib/json/__init_.py
最常用的功能:
|
函数 |
描述 |
|
json.dumps |
将 Python 对象编码成 JSON 字符串 |
|
json.loads |
将已编码的 JSON 字符串解码为 Python 对象 |
|
json.dump |
将数据写入json文件中 |
|
json.load |
从json文件中读取数据 |
2. 使用
2.1. json.dump
json.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)
将对象按格式转换表转化为JSON格式流写入文件(准确来说是文件句柄,也支持写入数据写入类文件句柄)
skipkeys:如果为True,非基本类型键(str,int,float,bool,None)会被跳过并抛出一个TypeError异常。
ensure_ascii:如果为真(默认),输入进行转义;为否则不进行转义。
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
with open('a.txt', 'w', encoding='utf-8') as fi:
js_dump = json.dump(data, fi)
print(js_dump)
2.2. json.dumps
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
与json.dump()基本类似,除了不写入文件而是返回一个str对象。
需要注意的是JSON中键/值对的键总是str类型的,当一个字典转化为JSON格式,所有的键都被转化为字符串。
而这会导致存在非字符串键时有loads(dumps(x)) != x
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
js = json.dumps(data)
print(type(js)) #<class 'str'>
2.3. json.load
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
从文件中读取数据
a = [1,2,3,4,5,6,7,8,9]
with open('a.txt', 'w', encoding='utf-8') as fi:
js_dump = json.dump(a, fi)
with open('a.txt', 'r', encoding='utf-8') as fi:
data = json.load(fi)
print(type(data)) #<class ‘list’>
2.4. json.loads
json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
将str,bytes,bytearray类型的实例转换为python对象。
js = json.loads(json_str)
2.5. 编码与解码
class json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
Simple JSON decoder.
格式转换对应表:
|
JSON |
Python |
|
object |
dict |
|
array |
list |
|
string |
str |
|
number (int) |
int |
|
number (real) |
float |
|
true |
True |
|
false |
False |
|
null |
None |
class json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶
Extensible JSON encoder for Python data structures.
格式转换对应表:
|
Python |
JSON |
|
dict |
object |
|
list, tuple |
array |
|
str |
string |
|
int, float, int- & float-derived Enums |
number |
|
True |
true |
|
False |
false |
|
None |
null |
2.6. exceptions
exception json.JSONDecodeError(msg, doc, pos)
Subclass of ValueError with the following additional attributes:
msg:
The unformatted error message.
doc
The JSON document being parsed.
pos
The start index of doc where parsing failed.
lineno
The line corresponding to pos.
colno
The column corresponding to pos.
笔记-python-standard library-19.2 json的更多相关文章
- Python语言中对于json数据的编解码——Usage of json a Python standard library
一.概述 1.1 关于JSON数据格式 JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 46 ...
- The Python Standard Library
The Python Standard Library¶ While The Python Language Reference describes the exact syntax and sema ...
- Python Standard Library
Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...
- 《The Python Standard Library》——http模块阅读笔记1
官方文档:https://docs.python.org/3.5/library/http.html 偷个懒,截图如下: 即,http客户端编程一般用urllib.request库(主要用于“在这复杂 ...
- 《The Python Standard Library》——http模块阅读笔记2
http.server是用来构建HTTP服务器(web服务器)的模块,定义了许多相关的类. 创建及运行服务器的代码一般为: def run(server_class=HTTPServer, handl ...
- 《The Python Standard Library》——http模块阅读笔记3
http.cookies — HTTP state management http.cookies模块定义了一系列类来抽象cookies这个概念,一个HTTP状态管理机制.该模块支持string-on ...
- Python Standard Library 学习(一) -- Built-in Functions 内建函数
内建函数列表 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() ...
- [译]The Python Tutorial#10. Brief Tour of the Standard Library
[译]The Python Tutorial#Brief Tour of the Standard Library 10.1 Operating System Interface os模块为与操作系统 ...
- C++11新特性——The C++ standard library, 2nd Edition 笔记(一)
前言 这是我阅读<The C++ standard library, 2nd Edition>所做读书笔记的第一篇.这个系列基本上会以一章一篇的节奏来写,少数以C++03为主的章节会和其它 ...
- [译]The Python Tutorial#11. Brief Tour of the Standard Library — Part II
[译]The Python Tutorial#Brief Tour of the Standard Library - Part II 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...
随机推荐
- orcale错题分析
删除同义词语法正确的是: Drop synonym sy nonym_name; 关于Oracle创建间隔分区后,正确的是: 使用partition(分区名)可以查看特定分区内存放的表记录 关于序列 ...
- ASP.NET Web.Config连接数据库(测试)
事先说明,我是看着http://jingyan.baidu.com/article/ff411625bc461712e5823775.html做的. web.Config代码(vs2010): 使用的 ...
- jstack的使用方法
背景 记得前段时间,同事说他们测试环境的服务器cpu使用率一直处于100%,本地又没有什么接口调用,为什么会这样?cpu使用率居高不下,自然是有某些线程一直占用着cpu资源,那又如何查看占用cpu较高 ...
- cf314E. Sereja and Squares(dp)
题意 题目链接 给你一个擦去了部分左括号和全部右括号的括号序列,括号有25种,用除x之外的小写字母a~z表示.求有多少种合法的括号序列.答案对4294967296取模.合法序列不能相交,如()[],( ...
- Android 仿电商app商品详情页按钮浮动效果
1.效果图如下: 这效果用户体验还是很酷炫,今天我们就来讲解如何实现这个效果. 2.分析 为了方便理解,作图分析 如图所示,整个页面分为四个部分: 1.悬浮内容,floatView 2.顶部内容,he ...
- Selenium常见元素定位方法和操作的学习介绍
参考地址: https://www.cnblogs.com/eastmount/p/4810690.html 这篇文章主要Selenium+Python自动测试或爬虫中的常见定位方法.鼠标操作.键盘操 ...
- 如何使用VS将项目生成一个安装包?
VS2010项目的部署与安装winform程序,我想进行安装.1.在解决方案中 ——点击右键——添加 2.然后选择 安装和部署 ——安装向导 可以更改名称 3.点击 下一步 4.然后选择上那3个 5. ...
- C++编写双向链表
创建双向链表类,该类有默认构造函数.类的拷贝函数.类的.实现链表添加数据.升序排序.查找链表中某个节点及删除链表中某个节点的操作 代码实现: #include<iostream> #inc ...
- python3爬虫03(find_all用法等)
#read1.html文件# <html><head><title>The Dormouse's story</title></head># ...
- 使用kubeadm搭建Kubernetes集群
记录在石墨日记中,经常更新,懒得再复制了,直接点击下面链接查看吧 移步到此: https://shimo.im/docs/22WbxxQa1WUV9wsN/