在Python中处理 JSON 数据
Python中JSON的介绍:
JSON 的完整形式是 JavaScript Object Notation。这意味着由编程语言中的文本组成的脚本(可执行)文件用于存储和传输数据。 Python通过一个名为 JSON 的内置包支持 JSON。要使用此功能,我们在Python脚本中导入 JSON 包。 JSON中的文本是通过quoted-string完成的,该字符串包含{}内键值映射中的值。它类似于Python中的字典。 JSON 显示了一个类似于标准库 marshal 和 pickle 模块的用户的 API, Python原生支持 JSON 功能。例如
Python3
# Python program showing
# use of json package
import json
# {key:value mapping}
a ={"name":"John",
"age":31,
"Salary":25000}
# conversion to JSON done by dumps() function
b = json.dumps(a)
# printing the output
print(b)
Python3
# Python program showing that
# json support different primitive
# types
import json
# list conversion to Array
print(json.dumps(['Welcome', "to", "GeeksforGeeks"]))
# tuple conversion to Array
print(json.dumps(("Welcome", "to", "GeeksforGeeks")))
# string conversion to String
print(json.dumps("Hi"))
# int conversion to Number
print(json.dumps(123))
# float conversion to Number
print(json.dumps(23.572))
# Boolean conversion to their respective values
print(json.dumps(True))
print(json.dumps(False))
# None value to null
print(json.dumps(None))
Python3
var = {
"Subjects": {
"Maths":85,
"Physics":90
}
}
Python3
with open("Sample.json", "w") as p:
json.dump(var, p)
Python3
with open("Sample.json", "r") as read_it:
data = json.load(read_it)
Python3
json_var ="""
{
"Country": {
"name": "INDIA",
"Languages_spoken": [
{
"names": ["Hindi", "English", "Bengali", "Telugu"]
}
]
}
}
"""
var = json.loads(json_var)
Python3
# storing marks of 3 subjects
var = [{"Math": 50, "physics":60, "Chemistry":70}]
print(demjson.encode(var))
Python3
var = '{"a":0, "b":1, "c":2, "d":3, "e":4}'
text = demjson.decode(var)
Python3
# Other Method of Encoding
json.JSONEncoder().encode({"foo": ["bar"]})
'{"foo": ["bar"]}'
# Using iterencode(object) to encode a given object.
for i in json.JSONEncoder().iterencode(bigobject):
mysocket.write(i)
Python3
# To encode and decode operations
import json
var = {'age':31, 'height'= 6}
x = json.dumps(var)
y = json.loads(var)
print(x)
print(y)
# when performing from a file in disk
with open("any_file.json", "r") as readit:
x = json.load(readit)
print(x)
Python3
import requests
import json
# Now we have to request our JSON data through
# the API package
res = requests.get("https://jsonplaceholder.typicode.com / todos")
var = json.loads(res.text)
# To view your Json data, type var and hit enter
var
# Now our Goal is to find the User who have
# maximum completed their task !!
# i.e we would count the True value of a
# User in completed key.
# {
# "userId": 1,
# "id": 1,
# "title": "Hey",
# "completed": false, # we will count
# this for a user.
# }
# Note that there are multiple users with
# unique id, and their task have respective
# Boolean Values.
def find(todo):
check = todo["completed"]
max_var = todo["userId"] in users
return check and max_var
# To find the values.
Value = list(filter(find, todos))
# To write these value to your disk
with open("sample.json", "w") as data:
Value = list(filter(keep, todos))
json.dump(Value, data, indent = 2)
输出:
{"age": 31, "Salary": 25000, "name": "John"}
如您所见,JSON 支持原始类型,如字符串和数字,以及嵌套列表、元组和对象
Python3
# Python program showing that
# json support different primitive
# types
import json
# list conversion to Array
print(json.dumps(['Welcome', "to", "GeeksforGeeks"]))
# tuple conversion to Array
print(json.dumps(("Welcome", "to", "GeeksforGeeks")))
# string conversion to String
print(json.dumps("Hi"))
# int conversion to Number
print(json.dumps(123))
# float conversion to Number
print(json.dumps(23.572))
# Boolean conversion to their respective values
print(json.dumps(True))
print(json.dumps(False))
# None value to null
print(json.dumps(None))
输出:
["Welcome", "to", "GeeksforGeeks"]
["Welcome", "to", "GeeksforGeeks"]
"Hi"
123
23.572
true
false
null
序列化 JSON:
编码 JSON 的过程通常称为序列化。该术语是指将数据转换为一系列字节(因此是串行的)以通过网络存储或传输。为了处理文件中的数据流, Python中的 JSON 库使用 dump()函数将Python对象转换为各自的 JSON 对象,因此可以轻松地将数据写入文件。请参见下表。Python object JSON object dict object list, tuple array str string int, long, float numbers True true False false None null
序列化示例:
考虑给定的Python对象示例。
Python3
var = {
"Subjects": {
"Maths":85,
"Physics":90
}
}
使用 Python 的上下文管理器,创建一个名为 Sample.json 的文件并以写入模式打开它。
Python3
with open("Sample.json", "w") as p:
json.dump(var, p)
在这里,dump() 首先有两个参数,要序列化的数据对象,其次是要写入的对象(字节格式)。
反序列化 JSON:
反序列化与序列化相反,即将 JSON 对象转换为它们各自的Python对象。 load() 方法用于它。如果你使用过其他程序的 JSON 数据,或者获取的 JSON 的字符串格式,那么很容易用 load() 进行反序列化,通常是从字符串加载,否则,根对象在 list 或 dict 中.
Python3
with open("Sample.json", "r") as read_it:
data = json.load(read_it)
反序列化示例:
Python3
json_var ="""
{
"Country": {
"name": "INDIA",
"Languages_spoken": [
{
"names": ["Hindi", "English", "Bengali", "Telugu"]
}
]
}
}
"""
var = json.loads(json_var)
编码和解码:
编码被定义为将文本或值转换为加密形式,只有通过解码才能由所需用户使用。这里对 JSON(对象)格式进行编码和解码。编码也称为序列化,解码称为反序列化。 Python有一个用于此操作的流行包。这个包被称为Demjson 。要安装它,请按照以下步骤操作。
对于 Windows:
pip install demjson
对于 Ubuntu:
sudo apt-get update
sudo apt-get install python-demjson
编码:encode()函数用于将Python对象转换为 JSON字符串表示。
Syntax: demjson.encode(self, obj, nest_level=0)
示例 1:使用 demjson 包进行编码。
Python3
# storing marks of 3 subjects
var = [{"Math": 50, "physics":60, "Chemistry":70}]
print(demjson.encode(var))
输出:
[{"Chemistry":70, "Math":50, "physics":60}]
解码:decode()函数用于将 JSON 对象转换为 python 格式类型。
Syntax : demjson.decode(self, obj)
示例 2:使用 demjson 包解码
Python3
var = '{"a":0, "b":1, "c":2, "d":3, "e":4}'
text = demjson.decode(var)
输出:
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
示例 3:使用 iterencode 包进行编码
Python3
# Other Method of Encoding
json.JSONEncoder().encode({"foo": ["bar"]})
'{"foo": ["bar"]}'
# Using iterencode(object) to encode a given object.
for i in json.JSONEncoder().iterencode(bigobject):
mysocket.write(i)
示例 4:使用 dumps() 和 loading() 进行编码和解码。
Python3
# To encode and decode operations
import json
var = {'age':31, 'height'= 6}
x = json.dumps(var)
y = json.loads(var)
print(x)
print(y)
# when performing from a file in disk
with open("any_file.json", "r") as readit:
x = json.load(readit)
print(x)
命令行用法
JSON 库也可以从命令行使用,以验证和漂亮地打印您的 JSON。
$ echo "{ \"name\": \"Monty\", \"age\": 45 }"
使用 JMESPath 搜索 JSON
JMESPath 是一种 JSON 查询语言。它使您可以轻松地从 JSON 文档中获取所需的数据。如果您以前使用过 JSON,您可能知道获取嵌套值很容易。例如, doc[“person”][“age”] 将为您获取文档中年龄的嵌套值。
首先,安装 jmespath :
$ pip3 install jmespath
真实世界的例子:
让我们举一个在Python中实现 JSON 的真实例子。 JSON_placeholder 是一个很好的实践来源,它提供了一个很棒的 API 请求包,我们将在示例中使用它。要开始,请按照以下简单步骤操作。打开Python IDE 或 CLI 并创建一个新的脚本文件,将其命名为 sample.py。
Python3
import requests
import json
# Now we have to request our JSON data through
# the API package
res = requests.get("https://jsonplaceholder.typicode.com / todos")
var = json.loads(res.text)
# To view your Json data, type var and hit enter
var
# Now our Goal is to find the User who have
# maximum completed their task !!
# i.e we would count the True value of a
# User in completed key.
# {
# "userId": 1,
# "id": 1,
# "title": "Hey",
# "completed": false, # we will count
# this for a user.
# }
# Note that there are multiple users with
# unique id, and their task have respective
# Boolean Values.
def find(todo):
check = todo["completed"]
max_var = todo["userId"] in users
return check and max_var
# To find the values.
Value = list(filter(find, todos))
# To write these value to your disk
with open("sample.json", "w") as data:
Value = list(filter(keep, todos))
json.dump(Value, data, indent = 2)
要了解更多,请点击这里