在 Django 中导致错误的有效 (?) JSON 数据必须作为字符串提供给前端并由 JSON.parse() 在 javascript 中转换 - 为什么?

尤金·伊根

我在 Django 目录中本地托管了一个 JSON 文件。它从该文件中提取到views.py 中的一个视图,在那里它被读入如下:

def Stops(request):
   json_data = open(finders.find('JSON/myjson.json'))
   data1 = json.load(json_data)  # deserialises it
   data2 = json.dumps(data1)  # json formatted string
   json_data.close()
   return JsonResponse(data2, safe=False)

在没有 (safe=False) 的情况下使用 JsonResponse 会返回以下错误:

TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.

同样,使用 json.loads(json_data.read()) 而不是 json.load 会出现此错误:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这让我感到困惑 - 我已经使用在线验证器验证了 JSON。当使用 safe=False 将 JSON 发送到前端时,到达的结果对象是一个字符串,即使在 javascript 中调用 .json() 之后也是如此:

fetch("/json").then(response => {
     return response.json();
     }).then(data => {
     console.log("data ", data); <---- This logs a string to console
...

但是,再走一步并在字符串上调用 JSON.parse() 会将对象转换为我可以按预期使用的 JSON 对象

       data = JSON.parse(data);
       console.log("jsonData", data); <---- This logs a JSON object to console

但是这个解决方案并没有让我觉得是一个完整的解决方案。

在这一点上,我认为最有可能的事情是源 JSON 有问题 - (在文件字符编码中?)或者 json.dumps() 没有做我认为应该做的事情,或者我不理解Django API 的 JSONresponse 函数以一种我不知道的方式......

我已经达到了我对这个主题的知识极限。如果您有任何智慧可以传授,我将不胜感激。

编辑:正如 Abdul 在下面的回答中一样,我将 JSON 重新格式化为带有 json.dumps(data1) 行的字符串

工作代码如下所示:

def Stops(request):
   json_data = open(finders.find('JSON/myjson.json'))
   data = json.load(json_data)  # deserialises it
   json_data.close()
   return JsonResponse(data, safe=False)  # pass the python object here
阿卜杜勒·阿齐兹·巴尔卡特

让我们看看您的代码的以下几行:

json_data = open(finders.find('JSON/myjson.json'))
data1 = json.load(json_data)  # deserialises it
data2 = json.dumps(data1)  # json formatted string

您打开一个文件,并得到一个文件指针json_data,分析它的内容,并得到一个Python对象data1,然后把它JSON字符串,并将其存储data2有点多余吧?接下来,您将此 JSON 字符串传递给JsonResponse它将进一步尝试将其序列化为 JSON!这意味着您随后会在 JSON 中的字符串中获得一个字符串。

请尝试以下代码:

def Stops(request):
   json_data = open(finders.find('JSON/myjson.json'))
   data = json.load(json_data)  # deserialises it
   json_data.close()
   return JsonResponse(data, safe=False)  # pass the python object here

注意:python 中的函数名最好在snake_casenot 中PascalCase,因此Stops你应该使用stops. 请参阅PEP 8 -- Python 代码风格指南

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章