f0rd42
f0rd42

Reputation: 1449

json.dumps need additional "," between entries

my json.dumps code:

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

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=(', ', ': '))

Upvotes: 0

Views: 57

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

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)

Upvotes: 3

Related Questions