我的前端应该从后端接收一个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字符串,结果仍然是一样的。这真令人沮丧
我尝试在另一个对
JSON.parse()
的调用中包装JSON.parse()
的输出,并且我能够以我想要的方式索引结果对象我不确定我是否完全理解发生了什么,但我想没有必要在我的
views.py
文件中运行json.dumps()
,因为settings.GUEST_USER_CREDENTIALS
已经是JSON了从
views.py
中删除json.dumps()
并按原样将settings.GUEST_USER_CREDENTIALS
添加到上下文中,就不需要在前端对JSON.parse()
进行两次调用,现在一切都按预期进行相关问题 更多 >
编程相关推荐