【发布时间】:2021-10-15 09:32:31
【问题描述】:
我的前端应该从后端接收一个 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 字符串,结果还是一样。这太令人沮丧了。
【问题讨论】:
-
您的代码在 Javascript 中适用于我。我可以做
JSON.parse(s)['EMAIL']或JSON.parse(s).EMAIL。 -
@TimRoberts 我都试过了,都返回
undefined。您是否像示例中那样从 Django 后端传递了字符串?
标签: javascript python json django typescript