2017-07-24 246 views
-2

我想知道从python的for循环中的最后一行中删除逗号需要什么。当我运行脚本时,它给了我下面的输出(在代码段之后)。我想删除第四行末尾的逗号“{”{#MACRO}“:”queue4“},”请问有人可以帮忙吗?Python在for循环中删除最后一行的逗号

顺便说一下,如果有更好的方法来构建块请分享想法。我是初学者,喜欢学习。 :)

代码:

import json 
import urllib 
import string 

Url= "http://guest:[email protected]:55672/api/queues" 
Response = urllib.urlopen(Url) 
Data = Response.read() 

def Qlist(Name): 
    Text = ''' {{"{{#MACRO}}":"{Name}"}},'''.format(Name=Name) 
    print Text 

X_json = json.loads(Data) 

print '''{ 
"data":[''' 
for i in X_json: 
    VV = i['name'] 
    Qlist(VV) 
print '''] 
}''' 

下面是输出:

{ 
"data":[ 
    {"{#MACRO}":"queue1"}, 
    {"{#MACRO}":"queue2"}, 
    {"{#MACRO}":"queue3"}, 
    {"{#MACRO}":"queue4"}, 
] 
} 

非常感谢

+2

从来没有,永远* *手工拼凑JSON或任何其他数据序列化格式。建立一个Python列表/字典和'json.dumps'它! – deceze

+0

使用连接。将格式化的名称添加到列表中。最后做','join(格式化的名单)。 – Kajal

+0

@deceze。您可以请帮助介绍json转储代码。正如你可能已经想出了我有一个rabbitmq实现4队列,并试图抓住他们的名字,以给定的块。请注意,尽管与关键字“数据”一致:[在块的开始处必须具有这一行。请我是一名学生,如果你编写代码,它会帮助我很多。非常感谢 – bindo

回答

4

你可以修改你的循环如下。

# Create and initialize a dictionary (Associative Array) 
# data['data'] is an empty list. 
# Variable name (data in this case) can be anything you want. 
# 'data' is a key. notice the quotations around. it's not a variable. 
# I used 'data' as the key, becasue you wanted your final output to include that part. 
data = {"data": []} 

for i in X_json: 

    # We are not calling the data dictionary here. 
    # We are accessing the empty list we have created inside the `data` dict (above) using data['data'] syntax. 
    # We can use the append function to add an item to a list. 
    # We create a new dictionary for every `name` item found in your json array and 
    # append that new dictionary to the data['data'] list. 
    data['data'].append({"{#MACRO}": i['name']}) 

print(json.dumps(data)) 
# or print json.dumps(data, indent=True) 

了解更多关于json.dumps()here。你可以阅读更多关于Python的listdictionaryhere

+0

非常感谢你的朋友。你的代码完美地工作。作为一个初学者我很想知道这里正在做什么。我不承认的部分是'data = {“data”:[]}'并且在for循环中'data ['data']。append({“{#MACRO}”:i ['name']} )' 请问你会解释为什么'data'在for循环中被再次调用?您已将“数据”分配给称为数据的变量以及循环之前,因此无法在循环内调用它?再次感谢好友。 – bindo

+0

如果您可以使用注释修改代码我认为它会更容易理解,而不是在评论框中回复。 :) – bindo

+0

谢谢很多人。现在它非常有意义。你是个天才。任何机会如果你可以给我你的电子邮件。或者将我指向你的个人资料,以便我可以自己找到它。 – bindo

-1

不要printQlist - 而不是return的值;那么你可以加入使用逗号作为分隔所有返回的值:

def Qlist(Name): 
    Text = ''' {{"{{#MACRO}}":"{Name}"}}'''.format(Name=Name) 
    return Text 

print '''{ 
"data":[''' + 
',\n'.join([ Qlist(i['name']) for i in X_json ]) + 
'''] 
}''' 

不管怎样,使用json.dumps可能是一个更好的主意。

+0

非常感谢。如果你可以请帮我用json.dumps代码。请阅读我在上面提供的评论中给出的评论。非常感谢。 – bindo

相关问题