0

I have json file like this:

{
    "url": {
        "188.40.0.138\n": {
            "bytes": 13882,
            "code": 403
        },
        "iantivirus.us\n": {
            "bytes": 13563,
            "code": 503
        },
        "ibmsupport.net\n": {
            "bytes": 13648,
            "code": 503
        },
        "usbnak.com\n": {
            "bytes": 13779,
            "code": 403
        }
    }
}

i want to convert this into a csv file with following format: url,188.40.0.138\n,13882.403

when i uses (say this is loaded to variable data)

for i in data['url']"
    print i['status'] # says index should be integer
    print i # prints 188.40.0.138\n
    print i[0:3] #prints 188.

the problem here is i am unable to access inner elements

1
  • Is 'url' static? Did you mean to write url,188.40.0.138\n,13882.403, then url,iantivirus.us\n, 13563, etc. or should url be omitted? Are there other keys in data? Commented May 1, 2014 at 9:30

2 Answers 2

1

Your i is just the key; you'd have to look up data['url'][i] to get the nested dictionary.

You can nest the loop, using dict.iteritems() (Python 2) or dict.items() (Python 3):

for url, items in data.iteritems():
    for item, value in items.iteritems():
        print url, item, value['bytes']

If you plan to write CSV, use the csv module:

import csv

with open('output.csv', 'wb') as outfh:
    writer = csv.writer(outfh)
    for url, items in data.iteritems():
        for item, value in items.iteritems():
            writer.writerow([url, item, value['bytes']])
Sign up to request clarification or add additional context in comments.

Comments

0
for i,k in data.iteritems():
    for y,z in k.iteritems():
        print "url,%s,%s.%s"%(y,z.get('bytes'),z.get('code'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.