简体   繁体   English

json.dumps条目之间需要额外的“,”

[英]json.dumps need additional “,” between entries

my json.dumps code: 我的json.dumps代码:

print json.dumps({'cidr': item, 'name': 'Malware'}, sort_keys=True, indent=4, separators=(', ',    ': '))

work fine so far, as it outputs: 到目前为止工作正常,它输出:

    {
    "cidr": "98.131.229.2/32", 
    "name": "Malware"
    }
    {
    "cidr": "98.158.178.231/32", 
    "name": "Malware"
    }

I need two additional things 我还需要两件事

  • a opening and closing bracket [ ] (first and last line) 开闭括号[ ] (第一行和最后一行)
  • an additional , between the entries 一个额外的,所述条目之间

I tried is with a loop, but that brings me the additional , also at the end (just before the closing ] 我尝试过使用一个循环,但这给我带来了额外的效果,也包括最后(就在结束之前)

so, in the end, I need an output like: 因此,最后,我需要一个类似的输出:

[
{
    "cidr": "98.131.229.2/32", 
    "name": "Malware"
}
,
{
    "cidr": "98.158.178.231/32", 
    "name": "Malware"
}
]

Can I do this with the standard son tools or do I need to run additional stuff? 我可以使用标准子工具执行此操作,还是需要运行其他内容?

I'm not working with dictionaries. 我不在和字典一起工作。 Full code: 完整代码:

malwareurl = "http://www.malwaredomainlist.com/hostslist/ip.txt"  # URL to TXT file

    print "Downloading with urllib2"
    f = urllib2.urlopen(malwareurl)
    result = f.read().split("\r\n")
    ips = [x + "/32" for x in result if x]

    for item in ips:
        print json.dumps({'cidr': item, 'name': 'Malware'}, sort_keys=True, indent=4, separators=(', ', ': '))

The solution is to build a list, then dump the list: 解决方案是建立一个列表,然后转储该列表:

result = []
for item in ips:
    result.append({'cidr': item, 'name': 'Malware'})

print json.dumps(result)

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

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