Django中读取json为字典

读取本地JSON文件,期望使用return JsonResponse返回前端,JSON文件的格式如下:

[
  {
    "id": "1",
    "text": "节点 1",
    "children": [
      {
        "id": "1.1",
        "text": "子节点 1.1",
        "children": [
          { "id": "1.1.1", "text": "叶子节点 1.1.1" },
          { "id": "1.1.2", "text": "叶子节点 1.1.2" }
        ]
      },
      { "id": "1.2", "text": "子节点 1.2" }
    ]
  },
  {
    "id": "2",
    "text": "节点 2",
    "children": [
      { "id": "2.1", "text": "子节点 2.1" },
      { "id": "2.2", "text": "子节点 2.2" }
    ]
  }
]

读取JSON后LOAD输出的是一个列表,应当怎么转换成字典的类型以便JsonResponse返回

    module_dir = os.path.dirname(__file__)
    file_path = os.path.join(module_dir, 'caseTree.json')

    with open(file_path, 'r', encoding='utf8') as t:
        js = json.load(t)

return JsonResponse(js, safe=False, json_dumps_params={'ensure_ascii': False})

return JsonResponse(js, safe=False)

safe参数设为False,这样,你可以直接返回你读取的JSON文件内容,不需要转换成字典。


如果有帮助,请点击一下采纳该答案~谢谢

  • 这篇博客: Django 返回json数据中的 JsonResponse的源码 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • class JsonResponse(HttpResponse):
        """
        An HTTP response class that consumes data to be serialized to JSON.
    
        :param data: Data to be dumped into json. By default only ``dict`` objects
          are allowed to be passed due to a security flaw before EcmaScript 5. See
          the ``safe`` parameter for more information.
        :param encoder: Should be a json encoder class. Defaults to
          ``django.core.serializers.json.DjangoJSONEncoder``.
        :param safe: Controls if only ``dict`` objects may be serialized. Defaults
          to ``True``.
        :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
        """
    
        def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                     json_dumps_params=None, **kwargs):
            if safe and not isinstance(data, dict):
                raise TypeError(
                    'In order to allow non-dict objects to be serialized set the '
                    'safe parameter to False.'
                )
            if json_dumps_params is None:
                json_dumps_params = {}
            kwargs.setdefault('content_type', 'application/json')
            data = json.dumps(data, cls=encoder, **json_dumps_params)
            super().__init__(content=data, **kwargs)
    

    其内部也是通过json.dumps来把数据转换为JSON的,其还可以转换为list类型。我们再来改一下testjson

    1 def testjson(request):
    2     listdata = ["张三", "25", "19000347", "上呼吸道感染"]
    3     return JsonResponse(listdata)
    

    程序报错了
    在这里插入图片描述
    报错为:In order to allow non-dict objects to be serialized set the safe parameter to False,它的意思是转换为一个非字典的类型时,safe参数要设置为False,还记得上面JsonResponse的原码吗?其中就有
    在这里插入图片描述
    代码修改为:

    def testjson(request):
        listdata = ["张三", "25", "19000347", "上呼吸道感染"]
        return JsonResponse(listdata, safe=False)
    

    在这里插入图片描述在这里插入图片描述在这里插入图片描述