Open dululu opened 6 months ago
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于在不同应用程序之间传输和存储结构化数据。它基于JavaScript语法,但已成为一种独立于编程语言的通用数据格式。 以下是JSON的一些特点和常见用法:
- 数据结构:JSON数据由键值对组成,类似于字典或映射的结构。键是字符串,值可以是字符串、数字、布尔值、数组、嵌套的JSON对象或null。
{ "name": "John", "age": 30, "isStudent": false, "scores": [95, 85, 90], "address": { "street": "123 Main St", "city": "New York" }, "contact": null }
- 大多数编程语言中,都提供了用于解析和生成JSON的库和函数。这些工具可以将JSON数据解析为对应的数据结构(如字典、列表)或对象,并将数据结构转换为JSON格式的字符串。
import json
json_str = '{"name": "John", "age": 30}' data = json.loads(json_str) print(data["name"]) # 输出: John
data = {"name": "John", "age": 30} json_str = json.dumps(data) print(json_str) # 输出: {"name": "John", "age": 30}
urllib3
是一个Python
的第三方库,用于在HTTP
请求中处理连接池、编码、重试等功能。它提供了一个高级的HTTP
客户端接口,简化了与Web服务器进行通信的过程。urllib3
库可以进行HTTP
请求的发送和处理。可以创建PoolManager
对象来管理连接池,并使用该对象发送GET
、POST
等类型的请求。urllib3
提供了对请求和响应的各种处理方法,例如设置请求头部、处理响应内容等。以下是一个使用urllib3发送GET请求的简单示例:
HEAD请求和GET请求在HTTP协议中是两种不同的请求方法,
GET
请求会返回请求的资源内容,包括响应头部和响应体。而HEAD
请求只返回响应头部,不返回响应体内容。因此,HEAD请求可以用于仅获取资源的元数据或检查资源是否存在,而不需要获取实际内容。更灵活地处理请求和响应。
在上面的示例中,我们定义了一个字典
headers
,包含了自定义的请求头部信息,并将其作为headers
参数传递给请求方法。在上面的示例中,我们定义了一个字典
params
,包含了查询参数的键值对,并将其作为fields
参数传递给GET请求方法。body
参数或fields
参数来传递请求数据。如果需要发送JSON
格式的数据,可以使用json
参数。例如:data = { 'name': 'John Doe', 'age': 30 } encoded_data = json.dumps(data).encode('utf-8')
response = http.request('POST', 'http://www.example.com', body=encoded_data, headers={'Content-Type': 'application/json'})