笔记-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. 内容显示分页数字分页 aspx

    此处是aspx里面分页显示,数据层和业务层是由动软生成 当然,我们也可以可以利用listView实现分页ListView(高效分页) public partial class NewList : Sy ...

  2. 导入maven多模块项目 出现的问题

    近日导入maven多模块项目 出现的问题以及解决过程2017年12月04日 20:43:04 守望dfdfdf 阅读数:815 标签: jdkmavenmaven pom.xml 更多个人分类: 工作 ...

  3. hibernate课程 初探单表映射1-4 hibernate开发前准备

    开发前准备: 1 eclipse 2 hibernate tools的安装(需要相关的jar包)(可以简化orm框架) hibernate tools的安装步骤: 1 到官网下载 https://so ...

  4. 在Magento中用MySQL模拟队列发送电子邮件

    1. 需求 顾客在网站上购买特定商品并且这些商品的总金额超过特定金额后,使用email给顾客发送一个优惠券:假如某件商品已经降价了,则此商品的金额不计算在目标总金额内: 2. 需求分析 ①发送优惠券的 ...

  5. java-jsch实现sftp文件操作

    (曾在天涯)的文章详细讲解了jsch中的函数以及用法 http://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html http://www. ...

  6. Windows下用cmd命令安装及卸载服务[转]

    第一种方法: 1. 开始 ->运行 ->cmd2. cd到C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727(Framework版本号按IIS配置) ...

  7. 怎么旋转PDF文件的方向并保存成功

    http://jingyan.baidu.com/article/59a015e39d7802f79488651e.html PDF格式的文档是非常普遍的一种阅读电子书格式,基本上非常好用了,不过有时 ...

  8. hihocoder第三十六周 二分查找

    题目链接:http://hihocoder.com/contest/hiho36/problem/1 , 一个比较简单的二分. 算法: 由于数据量比较大,O(nlogn)无法通过,所以不能先排序再查找 ...

  9. window下安装ubuntu(ubuntu可删除)

    进入ububtu13.04的安装界面,这里我们选择了“中文(简体)”,然后单击安装: 下图是现场拍的:   出现如下图时,请根据需要选择,然后单击“继续” , 接下来会出现问你是否要连接网络,我们选择 ...

  10. IntelliJ IDEA中激活JRebel插件

    1. 下载激活软件:https://github.com/ilanyu/ReverseProxy/releases/tag/v1.0 我下载的是 2. 双击文件运行 3. 点击change licen ...