笔记-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. 基于HttpClient的新版正方教务系统模拟登录及信息获取API

    简介 通过HttpClient获取网页数据源,通过Jsoup解析数据.先模拟登录,再获取信息.模拟浏览器正常操作,封装请求头信息获取SESSIONID.模拟登录成功后切勿断开会话,依赖登录请求得到的C ...

  2. Java 编码规范有感

    应小组要求,开发测试都需要考阿里编码规范,因此,相当于是突击了一下关于编码规范方面的知识,目前做的项目后期需要进行项目迁移,数据迁移,功能迁移... 各种迁移... 阿里巴巴编码规范(Java)考试地 ...

  3. li浮动 第二行第一个位置空白

    li浮动 第二行第一个位置空白:解决办法 li加上 vertical-align:bottom;overflow:hidden; 一行字多了 省略号代替: text-overflow: ellipsi ...

  4. mockJs语法糖用例

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  5. Git命令--保存用户名和密码

    使用git各项操作时,总是会出现输入密码的弹窗,且需要多次输入,很是繁琐,通过git命令可以记住密码,避免多次操作. 一.创建保存密码的文件 1.在home文件夹,一般是 C:\Documents a ...

  6. 解决mysql连接输入密码提示Warning: Using a password on the command line interface can be insecure

    有时候客户端连接mysql需要指定密码时(如用zabbix监控mysql)5.6后数据库会给出个警告信息 mysql -uroot -pxxxx Warning: Using a password o ...

  7. 在一个css文件中引入其他css文件

    @import "./main.css";@import "./color-dark.css";@import "./reset.css";

  8. PHP读取文件的常见方法

    整理了一下PHP中读取文件的几个方法,方便以后查阅. 1.fread string fread ( int $handle , int $length ) fread() 从 handle 指向的文件 ...

  9. 2018.2.5 PHP如何写好一个程序用框架

    随着PHP标准和Composer包管理工具的面世,普通开发者撸一个框架已经不再是什么难事了. 无论是路由管理.ORM管理.还是视图渲染都有许许多多优秀的包可以使用.我们就像堆积木一样把这些包用comp ...

  10. .net网站的下载地址

    .net4.0网址:http://www.crsky.com/soft/6959.htmlsql server r2: http://pan.baidu.com/share/link?shareid= ...