简体   繁体   English

如何用“枚举”迭代“ dict”

[英]How to iterate 'dict' with 'enumerate'

I have the following code. 我有以下代码。 This just show me one user instead of all the users I have inside my JSON, and also I have another problem, when I'm concatenating my strings it show me a "\\" after I put a '"': 这只是向我显示一个用户,而不是我在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')

在此处输入图片说明

I got registered two different users 我注册了两个不同的用户

在此处输入图片说明

With this code I need that all my users appear in http://127.0.0.1:8000/panel/api , but instead that, everytime I add a new one, is the unique that appear in here. 使用此代码,我需要所有用户都出现在http://127.0.0.1:8000/panel/api中 ,但是,每次我添加一个新用户时,该用户都将出现在此处。

In this image is the example, I added a new one and is the unique user I can visualize. 在此图像中,是示例,我添加了一个新示例,它是我可以看到的唯一用户。 在此处输入图片说明

The problem is that {'messages': myresponse} is a dictionary that has a string representing JSON* as a value to 'messages' , which is why you see the back-slash escapes behind the " character, because that is a json string , not a json-object. You should work entirely in the realm of python objects then deserialize at the end, don't mix the two, because you are getting exactly what you ask for. Instead: 问题是{'messages': myresponse}是一个字典 ,其中包含一个表示JSON *的字符串,作为'messages'的值,这就是为什么您看到反斜杠转义为"字符后的原因,因为这是一个json字符串 ,而不是json对象。您应该完全在python对象的领域中工作,然后最后反序列化,不要将两者混用,因为您将获得所需的结果,而是:

myresponse = [{"text":v} for v in dictionary.values()]

*Really, that string isn't even json, but it looks like a "tuple" of JSON-objects. *确实,该字符串甚至都不是json,但看起来像是JSON对象的“元组”。

To be more explicit, you are confusing the following two things, what you want is: 更明确地说,您混淆了以下两件事,您想要的是:

>>> d = {"foo":"bar"}
>>> json.dumps({"messeges":d})
'{"messeges": {"foo": "bar"}}'

What you are doing: 你在做什么:

>>> json.dumps({"messeges":'{"foo":"bar"}'}) # notice '{"foo":"bar"}' is a string
'{"messeges": "{\\"foo\\":\\"bar\\"}"}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM