Python JSON:编码(转储)、解码(加载)和读取 JSON 文件

JSON 是什么 Python?

JSON in Python 是受以下启发的标准格式: Java用于通过网络以文本格式进行数据交换和数据传输的脚本。通常,JSON 为字符串或文本格式。它可以被 API 和数据库使用,并以名称/值对的形式表示对象。JSON 代表 Java脚本对象符号。

Python JSON 语法:

JSON 以键和值对的形式写成。

{
        "Key":  "Value",
        "Key":  "Value",
} 

JSON 非常类似于 Python 字典。 Python 支持 JSON,并且它有一个内置的 JSON 库。

JSON 库 Python

元帅“和”泡菜' 外部模块 Python 维护一个版本 JSON Python 库。使用 JSON Python 要执行 JSON 相关操作(如编码和解码),您需要先 进口 JSON 库,并为此 的.py 文件,

import json

JSON 中有以下方法可用 Python 模块

付款方式 描述
转储() 编码为 JSON 对象
倾倒() 编码字符串写入文件
加载() 解码 JSON 字符串
加载() 读取 JSON 文件时进行解码

Python 转换为 JSON(编码)

JSON 图书馆 Python 执行以下翻译 Python 对象默认转换为 JSON 对象

Python JSON
字典 摆件
名单 排列
统一
数字 – int,长整型 数字 – int
浮动 数字 – 实数
没有

转换 Python 将数据转换为 JSON 称为编码操作。编码是在 JSON 库方法的帮助下完成的 - 转储()

JSON dumps() 在 Python

json.转储() in Python 是一种将字典对象转换为 Python 转换为 JSON 字符串数据格式。当对象需要采用字符串格式进行解析、打印等操作时,此功能很有用。

现在让我们执行第一个 json.dumps 编码示例 Python:

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice","Bob"),
  "pets": ['Dog'],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
  ]
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

输出:

{"person": {"name": "Kenn", "sex": "male", "age": 28}})

让我们看一个例子 Python 将 JSON 写入文件,使用相同函数创建字典的 JSON 文件 倾倒()

# here we create new data_file.json file with write mode using file i/o operation 
with open('json_file.json', "w") as file_write:
# write json data into file
json.dump(person_data, file_write)

输出:

没什么可显示的……在您的系统中创建了 json_file.json。您可以检查该文件,如下所示将 JSON 写入文件 Python 例。

Python JSON 编码示例

JSON 到 Python (解码)

JSON 字符串解码是通过内置方法完成的 json.loads() & json.load() JSON 库 Python。此处的翻译表显示了 JSON 对象的示例 Python 对象 这有助于执行解码 Python JSON 字符串。

JSON Python
摆件 字典
排列 名单
统一
数字 – int 数字 – int,长整型
数字 – 实数 浮动
没有

让我们看一个基本的 JSON 解析 Python 借助解码的示例 json.loads 功能,

import json  # json library imported
# json data string
person_data = '{  "person":  { "name":  "Kenn",  "sex":  "male",  "age":  28}}'
# Decoding or converting JSON format in dictionary using loads()
dict_obj = json.loads(person_data)
print(dict_obj)
# check type of dict_obj
print("Type of dict_obj", type(dict_obj))
# get human object details
print("Person......",  dict_obj.get('person'))

输出:

{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}
Type of dict_obj <class 'dict'>
Person...... {'name': 'John', 'sex': 'male'}

Python JSON 解码示例

解码 JSON 文件或解析 JSON 文件 Python

现在,我们将学习如何读取 JSON 文件 Python - Python 解析 JSON 示例:

注意: 解码 JSON 文件是文件输入/输出 (I/O) 相关操作。JSON 文件必须存在于您的系统中您在程序中提到的指定位置。

Python 读取JSON文件示例:

import json
#File I/O Open function for read data from JSON File
with open('X:/json_file.json') as file_object:
        # store file data in object
        data = json.load(file_object)
print(data)

这里的数据 是一个字典对象 Python 如上读取JSON文件 Python 例。

输出:

{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}

解析 JSON 文件 Python

紧凑编码 Python

当你需要减少 JSON 文件的大小时,可以使用紧凑编码 Python.

例,

import json
# Create a List that contains dictionary
lst = ['a', 'b', 'c',{'4': 5, '6': 7}]
# separator used for compact representation of JSON.
# Use of ',' to identify list items
# Use of ':' to identify key and value in dictionary
compact_obj = json.dumps(lst, separators=(',', ':'))
print(compact_obj)

输出:

'["a", "b", "c", {"4": 5, "6": 7}]'

** Here output of JSON is represented in a single line which is the most compact representation by removing the space character from compact_obj **

格式化 JSON 代码(美观打印)

  • 目的是编写格式良好的代码,方便人们理解。借助漂亮的打印功能,任何人都可以轻松理解代码。

示例:

import json
dic = { 'a': 4, 'b': 5 }
''' To format the code use of indent and 4 shows number of space and use of separator is not necessary but standard way to write code of particular function. '''
formatted_obj = json.dumps(dic, indent=4, separators=(',', ': '))
print(formatted_obj)

输出:

{
   "a" : 4,
   "b" : 5
}

格式 JSON 代码示例

为了更好地理解这一点,将缩进改为 40 并观察输出 -

格式 JSON 代码示例

对 JSON 代码进行排序:

排序键 归因于 Python dumps 函数的参数将按升序对 JSON 中的键进行排序。sort_keys 参数是一个布尔属性。当它为真时,允许排序,否则不允许。让我们通过 Python 字符串到 JSON 排序示例。

例,

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice", "Bob"),
  "pets": [ 'Dog' ],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
  	],
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

输出:

{
    "age": 45,
    "cars": [ {
        "model": "Audi A1", 
        "mpg": 15.1
    },
    {
        "model": "Zeep Compass", 
        "mpg": 18.1
    }
    ],
    "children": [ "Alice",
		  "Bob"
	],
    "married": true,
    "name": "Ken",
    "pets": [ 
		"Dog"
	]
}

您可能会发现钥匙的年龄、汽车、儿童等按升序排列。

复杂对象编码 Python

复杂对象有两个不同的部分

  1. 实部
  2. 虚部

复杂对象编码 Python

例如:3 +2i

在对复杂对象进行编码之前,您需要检查变量是否复杂。您需要创建一个函数,使用实例方法检查变量中存储的值。

让我们创建特定的函数来检查对象是否复杂或是否适合编码。

import json

# create function to check instance is complex or not
def complex_encode(object):
    # check using isinstance method
    if isinstance(object, complex):
        return [object.real, object.imag]
    # raised error using exception handling if object is not complex
    raise TypeError(repr(object) + " is not JSON serialized")


# perform json encoding by passing parameter
complex_obj = json.dumps(4 + 5j, default=complex_encode)
print(complex_obj)

输出:

'[4.0, 5.0]'

复杂 JSON 对象解码 Python

要解码 JSON 中的复杂对象,请使用 object_hook 参数来检查 JSON 字符串是否包含复杂对象。让我们来了解一下字符串转 JSON Python 例,

import json
  # function check JSON string contains complex object
  def is_complex(objct):
    if '__complex__' in objct:
      return complex(objct['real'], objct['img'])
    return objct
  
  # use of json loads method with object_hook for check object complex or not
  complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook = is_complex)
  #here we not passed complex object so it's convert into dictionary
  simple_object =json.loads('{"real": 6, "img": 7}', object_hook = is_complex)
  print("Complex_object......",complex_object)
  print("Without_complex_object......",simple_object)

输出:

Complex_object...... (4+5j)
Without_complex_object...... {'real': 6, 'img': 7}

JSON 序列化类 JSONEncoder 概述

JSONEncoder 类用于序列化任何 Python 执行编码时的对象。它包含三种不同的编码方法,分别是

  • 默认(o) – 在子类中实现并返回序列化对象 o 目的。
  • 编码(o) – 与 JSON 转储相同 Python 方法返回 JSON 字符串 Python 数据结构。
  • iterencode(o) – 逐个表示字符串并对对象o进行编码。

借助 JSONEncoder 类的 encode() 方法,我们还可以对任何 Python 如下所示的对象 Python JSON 编码器示例。

# import JSONEncoder class from json
from json.encoder import JSONEncoder
colour_dict = { "colour": ["red", "yellow", "green" ]}
# directly called encode method of JSON
JSONEncoder().encode(colour_dict)

输出:

'{"colour": ["red", "yellow", "green"]}'

JSON反序列化类JSONDecoder概述

JSONDecoder 类用于反序列化任何 Python 执行解码时的对象。它包含三种不同的解码方法,分别是

  • 默认(o) – 在子类中实现并返回反序列化的对象 o 目的。
  • 解码(o) – 与 json.loads() 方法返回相同 Python JSON字符串或数据的数据结构。
  • raw_decode(o) - 代表 Python 逐个字典并解码对象o。

借助 JSONDecoder 类的 decrypt() 方法,我们还可以解码 JSON 字符串,如下所示 Python JSON 解码器示例。

import json
# import JSONDecoder class from json
from json.decoder import JSONDecoder
colour_string = '{ "colour": ["red", "yellow"]}'
# directly called decode method of JSON
JSONDecoder().decode(colour_string)

输出:

{'colour': ['red', 'yellow']}

从 URL 解码 JSON 数据:真实示例

我们将从指定的 URL 获取 CityBike NYC(自行车共享系统)的数据(https://gbfs.citibikenyc.com/gbfs/2.3/gbfs.json) 并转换成字典格式。

Python 从文件加载 JSON 示例:

注意:- 确保请求库已安装在您的 Python, 如果没有,则打开终端或 CMD 并输入

  • (对于 Python 3或以上) pip3 安装请求
import json
import requests

# get JSON string data from CityBike NYC using web requests library
json_response= requests.get("https://gbfs.citibikenyc.com/gbfs/2.3/gbfs.json")
# check type of json_response object
print(type(json_response.text))
# load data in loads() function of json library
bike_dict = json.loads(json_response.text)
#check type of news_dict
print(type(bike_dict))
# now get stationBeanList key data from dict
print(bike_dict['stationBeanList'][0]) 

输出:

<class 'str'>
<class 'dict'>
{
	'id': 487,
 	'stationName': 'E 20 St & FDR Drive',
	'availableDocks': 24,
	'totalDocks': 34,
	'latitude': 40.73314259,
	'longitude': -73.97573881,
	'statusValue': 'In Service',
	'statusKey': 1,
	'availableBikes': 9,
	'stAddress1': 'E 20 St & FDR Drive',
	'stAddress2': '',
	'city': '',
	'postalCode': '',
	'location': '', 
	'altitude': '', 
	'testStation': False, 
	'lastCommunicationTime': '2018-12-11 10:59:09 PM', 'landMark': ''
}

与 JSON 库相关的异常 Python:

  • 增益级 json.JSONDecoderError 处理与解码操作相关的异常。它是 值错误。
  • 例外 - json.JSONDecoderError(msg,doc)
  • 异常的参数是,
    • msg – 未格式化的错误消息
    • doc – 解析后的 JSON 文档
    • pos – 失败时文档的起始索引
    • lineno – 行号显示对应 pos
    • 冒号 – 列号与位置不对应

Python 从文件加载 JSON 示例:

import json
#File I/O Open function for read data from JSON File
data = {} #Define Empty Dictionary Object
try:
        with open('json_file_name.json') as file_object:
                data = json.load(file_object)
except ValueError:
     print("Bad JSON file format,  Change JSON File")

JSON 库 Python

无限和 NaN Numbers in Python

JSON 数据交换格式 (RFC - 征求意见稿) 不允许无限值或 Nan 值,但没有限制 Python- JSON 库执行无限和 Nan 值相关操作。如果 JSON 获得 INFINITE 和 Nan 数据类型,则将其转换为文字。

例,

import json
# pass float Infinite value
infinite_json = json.dumps(float('inf'))
# check infinite json type
print(infinite_json)
print(type(infinite_json))
json_nan = json.dumps(float('nan'))
print(json_nan)
# pass json_string as Infinity
infinite = json.loads('Infinity')
print(infinite)
# check type of Infinity
print(type(infinite))

输出:

Infinity
<class 'str'>
NaN
inf
<class 'float'>	

JSON 字符串中的重复键

RFC 规定键名在 JSON 对象中应该是唯一的,但这不是强制性的。 Python JSON 库不会引发 JSON 中重复对象的异常。它会忽略所有重复的键值对,仅考虑其中的最后一个键值对。

  • 例,
import json
repeat_pair = '{"a":  1, "a":  2, "a":  3}'
json.loads(repeat_pair)

输出:

{'a': 3}

带有 JSON 的 CLI(命令行界面) Python

json.tool 提供命令行界面来验证 JSON 漂亮打印语法。让我们看一个 CLI 示例

带有 JSON 的命令行界面

$ echo '{"name" : "Kings Authur" }' | python3 -m json.tool

输出:

{
    "name": " Kings Authur "
}

JSON 的优点 Python

  • 轻松在容器和值之间来回切换(JSON 到 Python 和 Python 转换为 JSON)
  • 人类可读(漂亮打印) JSON 对象
  • 广泛应用于数据处理。
  • 单个文件中没有相同的数据结构。

JSON 的实现限制 Python

  • 在 JSON 范围的反序列化器中以及数字的预测
  • JSON 字符串和 JSON 数组的最大长度以及对象的嵌套级别。

Python JSON 速查表

Python JSON 函数 描述
json.dumps(person_data) 创建 JSON 对象
json.dump(person_data,file_write) 使用文件 I/O 创建 JSON 文件 Python
compact_obj = json.dumps(数据,分隔符=(',',':')) 通过使用分隔符从 JSON 对象中删除空格字符来压缩 JSON 对象
formatted_obj = json.dumps(dic,缩进=4,分隔符=(',',': ')) 使用缩进格式化 JSON 代码
sorted_string = json.dumps(x,缩进=4,sort_keys=True) 按字母顺序对 JSON 对象键进行排序
complex_obj = json.dumps(4 + 5j,默认=complex_encode) Python JSON 中的复杂对象编码
JSONEncoder().编码(颜色字典) 使用 JSONEncoder 类进行序列化
json.loads(数据字符串) 解码 JSON 字符串 Python 使用 json.loads() 函数的字典
json.loads('{“__complex__”:true,“real”:4,“img”:5}',object_hook = is_complex) 将复杂的 JSON 对象解码为 Python
JSONDecoder().解码(颜色字符串) 使用 JSON 解码 Python 反序列化