笔记-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 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...
随机推荐
- 50个必备的jQuery代码段
本文会给你们展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助.其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够帮助 ...
- android读写SD卡封装的类
参考了网上的一些资源代码,FileUtils.java: package com.example.test; import java.io.BufferedInputStream; import ja ...
- 使用vuex管理数据
src/vuex/store.js 组件里面使用引入store.js,注意路径 import store from 'store.js' 然后在使用的组件内data(){}同级放入store 三大常用 ...
- Vue.js(2.x)之插值
看了一些友邻写的文章,不少是基于1.0版本的,有些东西在2.x版本应该已经废除了(如属性插值.单次插值在2.x版本上运行根本不执行).对于不理解的东东,找起资料来就更麻烦了.不得不老老实实线下测试并整 ...
- windows下 php集成环境如何通过cmd执行命令
---恢复内容开始--- php学习过程中 Windows环境下的php集成程序很多 这样方便了学习 但是在熟悉命令使用方面可以说是十分不便 本文将从两个方便 向大家介绍如何快速通过cmd命令实现命令 ...
- Windows 10 取消桌面右键“图像属性”、“图像选项”
Windows 10 取消桌面右键"图像属性"."图像选项" 桌面右键 说明:在windows 10中,桌面右键出现"图像属性"." ...
- python基础-数据运算
*按位取反运算规则(按位取反再加1) 详解http://blog.csdn.net/wenxinwukui234/article/details/42119265 详细内容ht ...
- LNA与PA
LNA是低噪声放大器,主要用于接收电路设计中.因为接收电路中的信噪比通常是很低的,往往信号远小于噪声,通过放大器的时候,信号和噪声一起被放大的话非常不利于后续处理,这就要求放大器能够抑制噪声.PA(功 ...
- Dll注入:X86/X64 远程线程CreateRemoteThread 注入
远线程注入原理是利用Windows 系统中CreateRemoteThread()这个API,其中第4个参数是准备运行的线程,我们可以将LoadLibrary()填入其中,这样就可以执行远程进程中的L ...
- ubuntu16.4 配置logstash6.3.2 kibanan6.3.2
1. 官网下载 https://artifacts.elastic.co/downloads/logstash/logstash-6.3.2.tar.gz https://www.elastic.co ...