无法为后端解析的JSON字符串编制索引,它返回未定义的值

2024-10-02 00:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的前端应该从后端接收一个JSON字符串并使用它,但是当我在使用JSON.parse()之后尝试对它进行索引时,它返回undefined。我检查过了,它也不在数组中;它只是一个JSON对象文本

如果你们中的任何人不熟悉TypeScript,感叹号是一个TS的东西,删除它们不会改变我得到的结果

以下是控制台向我展示的内容:

console.log(document.getElementById('guestUserCredentials')!.textContent!)

"{\"EMAIL\": \"guest_user@foo.com\", \"PASSWORD\": \"foobar\"}"
console.log(JSON.parse(document.getElementById('guestUserCredentials')!.textContent!))

{"EMAIL": "guest_user@foo.com", "PASSWORD": "foobar"}
console.log(JSON.parse(document.getElementById('guestUserCredentials')!.textContent!)["EMAIL"])

undefined

也许这与Django后端编码JSON字符串的方式有关?如果是这样的话,我如何检查并修复它?我将它传递到我的React/TS前端,如下所示:

settings.py

...
GUEST_USER_CREDENTIALS = {
    'EMAIL': os.environ.get('GUEST_EMAIL'),
    'PASSWORD': os.environ.get('GUEST_PASSWORD'),
}
...

views.py

import json

from django.conf import settings
from django.shortcuts import render

def index(request, *args, **kwargs):

  print(settings.GUEST_USER_CREDENTIALS)
  print(json.dumps(settings.GUEST_USER_CREDENTIALS))

  return render(request, 'index.html', context={
    'GUEST_USER_CREDENTIALS': json.dumps(settings.GUEST_USER_CREDENTIALS),
  })

index.html

<!DOCTYPE html>
{% load static %}
<html>
<head>
  <meta charset='utf-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <link rel='icon' href='{% static "frontend/favicon.ico" %}' type='image/x-icon' />
  <title>foo</title>
</head>
<body>
<div id='root'>
  <!-- React goes here. -->
</div>
</body>
{{ GUEST_USER_CREDENTIALS|json_script:"guestUserCredentials" }}
<script src='{% static "frontend/index.bundle.js" %}'></script>
</html>

也许这与json_script模板标记转义JSON字符串中某些字符的方式有关I can't find anything about how that might affect the output in the documentation.

下面是views.py中两个print()命令的输出:

print(settings.GUEST_USER_CREDENTIALS)

{'EMAIL': 'guest_user@foo.com', 'PASSWORD': 'foobar'}
print(json.dumps(settings.GUEST_USER_CREDENTIALS))

{"EMAIL": "guest_user@foo.com", "PASSWORD": "foobar"}

我甚至尝试用destr而不是JSON.parse()解析JSON字符串,结果仍然是一样的。这真令人沮丧


Tags: 字符串jsonsettingsfooparseemailhtmlpassword
1条回答
网友
1楼 · 发布于 2024-10-02 00:29:50

我尝试在另一个对JSON.parse()的调用中包装JSON.parse()的输出,并且我能够以我想要的方式索引结果对象

我不确定我是否完全理解发生了什么,但我想没有必要在我的views.py文件中运行json.dumps(),因为settings.GUEST_USER_CREDENTIALS已经是JSON了

views.py中删除json.dumps()并按原样将settings.GUEST_USER_CREDENTIALS添加到上下文中,就不需要在前端对JSON.parse()进行两次调用,现在一切都按预期进行

相关问题 更多 >

    热门问题