笔记-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 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...
随机推荐
- asp.net5开发中DNX SDK版本的影响
某次asp.net5开发中遇到了一个很奇怪的问题,引用部分的nuget包没有显示任何错误,如下图: 但是编译时出现了几百个错误: 错误基本都是形如“CS0246 The type or namespa ...
- ASP.NET 中Textbox只能输入数字,不能输入其他字符
解决办法如下: <asp:TextBox ID="txtpage" runat="server" Width="61px" ...
- 提升Java代码质量(三)
Item7:覆盖equals时需要遵守通用约定 在我们日常开发过程中,重写equals是比较常用的,但存在许多不合适的覆盖方式导致错误,最好的避免方法就是不去重写equals.但有时我们的业务又需要建 ...
- String在方法中的传递方式(调用外部方法给String变量赋值时,未得到预期结果)
示例: public class StringTraining { public static void changeStr(String str){ str = "137878" ...
- Laravel事件监听器listener与事件订阅者Subscriber的区别
其实就一句话: Each event can have multiple listeners, but a listener can't listen to more than a single ev ...
- ArcGIS API for JavaScript开发初探——HelloMap
1.前言 在开始ArcGIS API for JavaScript开发之前我们需要了解一些基本的知识: 1.开发工具选什么? 前端技术的开发工具选择是一个仁者见仁智者见智的问题,有人喜欢Hbuilde ...
- 浅谈Scrum敏捷开发:4个输入/输出、3个关键物、3个会议
文章对Scrum敏捷开发流程进行系统的分析,希望借此文能够加深你对敏捷开发的认知,更好的展开产品工作. Scrum敏捷开发,是一种敏捷开发框架,是一个增量的.迭代的开发过程,具备可视.可集成和可运行使 ...
- 利用expect实现自动化操作
管理机上需要安装expect包 yum -y install expect 1.定义主机ip [root@localhost ~]# cat ip.txt 192.168.1.12 192.168.1 ...
- 企业常用的站内收索、QQ群、在线客服
<div class="toplinks"> <form target="_blank"> ...
- IOS 当一个控件被添加到父控件中会调用(didMoveToSuperview)
/** * 当一个控件被添加到父控件中就会调用 */ - (void)didMoveToSuperview { if (self.group.opened) { self.nameView.image ...