我有以下代码。这只显示了一个用户,而不是我在JSON中拥有的所有用户,而且我还有另一个问题,当我连接我的字符串时,它会在我放一个‘“’后显示一个"\”:
def get(self, request, format=None):
users = Caseworker.objects.all()
response = self.serializer(users, many=True)
for j in range(0,len(response.data)):
dictionary = response.data[j]
myresponse = ""
for i, (val, v) in enumerate(dictionary.items()):
myresponse = myresponse + '{"text":' + '"' + v + '"' + '}' + ','
print(myresponse)
# for i,(k,v) in enumerate(dictionary.items()):
# myresponse = myresponse + '{"text":' + '"' + v + '"' + '}' + ','
# print(myresponse)
return HttpResponse(json.dumps({'messages': myresponse}), content_type='application/json')

我注册了两个不同的用户

使用这段代码,我需要我的所有用户都出现在http://127.0.0.1:8000/panel/api中,但是每次我添加一个新用户时,它都是唯一的。
在此图像中是示例,我添加了一个新用户,并且是我可以可视化的唯一用户。

发布于 2018-01-16 15:29:59
问题是{'messages': myresponse}是一个字典,它有一个字符串将JSON*表示为'messages'的值,这就是为什么您会看到"字符后面的反斜杠转义,因为这是一个json字符串,而不是json对象。你应该完全在python对象的领域中工作,然后在最后反序列化,不要将两者混合在一起,因为你得到的正是你所要求的。而是:
myresponse = [{"text":v} for v in dictionary.values()]*实际上,该字符串甚至不是json,但它看起来像是JSON对象的“元组”。
更明确地说,你混淆了以下两件事,你想要的是:
>>> d = {"foo":"bar"}
>>> json.dumps({"messeges":d})
'{"messeges": {"foo": "bar"}}'您正在做的事情:
>>> json.dumps({"messeges":'{"foo":"bar"}'}) # notice '{"foo":"bar"}' is a string
'{"messeges": "{\\"foo\\":\\"bar\\"}"}'https://stackoverflow.com/questions/48275942
复制相似问题