You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中request.query_params解析异常,如何转为有效JSON?

解决Django request.query_params解析JSON格式参数异常的问题

当你在URL中传递JSON格式的查询参数(比如 example_param=[{"id":"f8","example_action":"kill"}])时,Django的request.query_params会将其解析为包含JSON字符串的列表,返回结果类似:

<QueryDict: {'example_param': ['[{"id":"f8", "example_action": "kill"}]']}>

这是因为HTTP查询参数本质是纯字符串键值对,Django不会自动识别并解析其中的JSON结构,需要手动处理。

处理步骤

直接提取参数对应的字符串,用Python标准库json解析即可:

import json
from django.http import HttpResponseBadRequest

# 从query_params中获取参数值,取列表的第一个元素(即使只有单个值,QueryDict也会返回列表)
param_str = request.query_params.get('example_param', '')
if param_str:
    try:
        # 解析为Python对象(这里是包含字典的列表)
        example_data = json.loads(param_str)
        # 后续可以正常使用example_data,比如访问example_data[0]['id']
    except json.JSONDecodeError:
        # 处理JSON格式错误的情况,比如返回400响应
        return HttpResponseBadRequest("Invalid JSON format for example_param")

注意事项

  • 如果前端传递的参数是多次重复的键(比如 example_param={"id":"f8"}&example_param={"id":"f9"}),request.query_params.getlist('example_param')会得到多个JSON字符串,此时需要逐个解析后合并。
  • 确保前端传递的JSON字符串是URL编码后的格式,避免特殊字符导致解析失败(比如空格、引号等)。

内容的提问来源于stack exchange,提问作者Ajax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 07:32:10