Python JSON与字典互转及Requests接口调用详解

周末不加班
周末不加班
发布时间:2026-10-13| 5人浏览过
原创

本文详解Python中JSON数据的基本操作。通过json.dumps实现字典转JSON字符串并处理中文编码,利用json.loads完成JSON转字典。同时介绍使用requests库调用API时,如何区分获取原始字符串与直接解析为字典对象,附带完整代码示例及运行结果分析。

JSON基本操作概述

JSON基本操作

导入JSON模块

首先需要导入json模块:import json

字典转JSON字符串

将字典转换为JSON字符串:使用json.dumps(dict, ensure_ascii=False)。添加ensure_ascii=False参数可确保转换后的字符串包含中文,避免乱码问题。

JSON字符串转字典

将JSON字符串转换为字典:使用json.loads(str)。

Requests接口获取JSON字典

通过requests库获取JSON数据:调用requests.get().json()可直接将响应内容解析为字典对象。

获取接口原始字符串

获取原始字符串:调用requests.get().text返回响应体的原始字符串内容。

完整代码示例

示例源码

核心代码实现


#!/usr/bin/python3
# encoding:utf-8
import json
import requests

class jsonC():
  def __init__(self):
    self.url = 'http://wthrcdn.etouch.cn/weather_mini?city=北京'
    self.geturl = requests.get(self.url)
  
  #字典转json,因为python没json类型所以str表示
  def dict_json(self):
    d = {"name":"张三","age":18}
    j = json.dumps(d,ensure_ascii=False)
    print('dict_json函数:类型:',type(d),'转类型',type(j),'\n',j)
  
  #json转字典  
  def json_dict(self):
    s = '{"name":"张三","age":18}'
    d = json.loads(s)
    print('json_dict函数:类型:',type(s),'转类型',type(d))
    
  #接口调用直接返回 字典(dict) 
  def get_json(self):
    d = self.geturl.json()
    print('get_json函数类型:',type(d))
  
  #接口调用直接返回字符串  
  def get_str(self):
    s = self.geturl.text
    print('get_str函数返回类型:',type(s))
    
if __name__=="__main__":
  js = jsonC()
  js.dict_json()
  js.json_dict()
  js.get_json()
  js.get_str()

代码运行结果分析

运行结果

dict_json函数输出显示类型从<class 'dict'>转换为<class 'str'>,内容为{"name": "张三", "age": 18}。 json_dict函数输出显示类型从<class 'str'>转换为<class 'dict'>。 get_json函数返回类型为<class 'dict'>。 get_str函数返回类型为<class 'str'>。

接口调用实战

调用get接口示例

请求URL:http://wthrcdn.etouch.cn/weather_mini?city=北京

返回的JSON数据值如下所示:

接口返回数据示例


{"data":
	{"yesterday":
		{"date":"28日星期六","high":"高温 30℃","fx":"西南风","low":"低温 17℃","fl":"<![CDATA[<3级]]>","type":"晴"},
		"city":"北京","forecast":
		[
			{"date":"29日星期天","high":"高温 29℃","fengli":"<![CDATA[<3级]]>","low":"低温 18℃","fengxiang":"南风","type":"晴"},
			{"date":"30日星期一","high":"高温 28℃","fengli":"<![CDATA[<3级]]>","low":"低温 19℃","fengxiang":"南风","type":"晴"},
			{"date":"1日星期二","high":"高温 29℃","fengli":"<![CDATA[<3级]]>","low":"低温 20℃","fengxiang":"南风","type":"多云"},
			{"date":"2日星期三","high":"高温 29℃","fengli":"<![CDATA[<3级]]>","low":"低温 17℃","fengxiang":"南风","type":"晴"},
			{"date":"3日星期四","high":"高温 30℃","fengli":"<![CDATA[<3级]]>","low":"低温 12℃","fengxiang":"东南风","type":"多云"}
		],"ganmao":"各项气象条件适宜,无明显降温过程,发生感冒机率较低。","wendu":"29"
	},"status":1000,"desc":"OK"
}

总结

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。