笔记-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的更多相关文章

  1. Python语言中对于json数据的编解码——Usage of json a Python standard library

    一.概述 1.1 关于JSON数据格式 JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 46 ...

  2. The Python Standard Library

    The Python Standard Library¶ While The Python Language Reference describes the exact syntax and sema ...

  3. Python Standard Library

    Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...

  4. 《The Python Standard Library》——http模块阅读笔记1

    官方文档:https://docs.python.org/3.5/library/http.html 偷个懒,截图如下: 即,http客户端编程一般用urllib.request库(主要用于“在这复杂 ...

  5. 《The Python Standard Library》——http模块阅读笔记2

    http.server是用来构建HTTP服务器(web服务器)的模块,定义了许多相关的类. 创建及运行服务器的代码一般为: def run(server_class=HTTPServer, handl ...

  6. 《The Python Standard Library》——http模块阅读笔记3

    http.cookies — HTTP state management http.cookies模块定义了一系列类来抽象cookies这个概念,一个HTTP状态管理机制.该模块支持string-on ...

  7. Python Standard Library 学习(一) -- Built-in Functions 内建函数

    内建函数列表 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() ...

  8. [译]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模块为与操作系统 ...

  9. C++11新特性——The C++ standard library, 2nd Edition 笔记(一)

    前言 这是我阅读<The C++ standard library, 2nd Edition>所做读书笔记的第一篇.这个系列基本上会以一章一篇的节奏来写,少数以C++03为主的章节会和其它 ...

  10. [译]The Python Tutorial#11. Brief Tour of the Standard Library — Part II

    [译]The Python Tutorial#Brief Tour of the Standard Library - Part II 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...

随机推荐

  1. 从零开始的全栈工程师——html篇1.8(知识点补充与浏览器兼容性)

    知识点补充 一.浏览器的兼容问题(关于浏览器的兼容问题 有很多大佬已经解释的很清楚了 这个得自己百度去多花点时间去了解 这里咱们只说一下前面的漏点) 浏览器兼容性问题又被称为网页兼容性或网站兼容性问题 ...

  2. 解决ie9以及以下console未定义

    页面明明已经删除了所有的console,但是ie9下依旧会报错 console未定义 只能这样解决了 window.console = window.console || (function () { ...

  3. Win10 应用商店管理应用

    在企业日常办公中,对 Windows 10 应用商店软件不需要,希望办公系统干净一些.企业运维中,我们可以使用组策略来管理Windows 10 微软Store应用程序.可以根据组织的要求进行配置,多项 ...

  4. 手机端@media screen布局自适应

    @media only screen and (min-width: 310px) and (max-width: 360px) { }@media only screen and (min-widt ...

  5. openstack RuntimeError: Unable to create a new session key. It is likely that the cache

    [Mon Apr 15 01:02:31.654247 2019] [:error] [pid 19433:tid 139790082479872] Login successful for user ...

  6. linux 命令——53 route(转)

    Linux系统的route 命令用于显示和操作IP路由表(show / manipulate the IP routing table).要实现两个不同的子网之间的通信,需 要一台连接两个网络的路由器 ...

  7. 2018.6.20 Java考试试题总结(Java语言基础与面向对象编程)最新版

    Java考试试题总结 一.单选题(每题1分 * 50 = 50分) 1.java程序的执行过程中用到一套JDK工具,其中javac.exe指( B ) A.java语言解释器 B.java字节码编译器 ...

  8. python_34_文件操作3

    f=open('yesterday',encoding='utf-8') print(f.tell())#文件句柄所在指针指向的位置,即光标在哪里(按字符计数) f.readline()#读一行 pr ...

  9. 01HTML

    1.认识HTML标记 2.元信息标记meta 2.1设置页面关键字 2.2设置页面说明 2.3定义编辑工具 2.4添加作者信息 2.5设置网页文字及语言 2.6设置网页的定时跳转 <html&g ...

  10. Maven 虐我千百遍,我待 Maven 如初恋

    前言 在如今的互联网项目开发当中,特别是Java领域,可以说Maven随处可见.Maven的仓库管理.依赖管理.继承和聚合等特性为项目的构建提供了一整套完善的解决方案,可以说如果你搞不懂Maven,那 ...