2

Have a file in plaintext that looks as follows:

{
   "user1":[int1, int2...intX], 
   "user2":[int1, int2...intX], 
    ... 
   "userX":[int1, int2...intX]
}

I want to be able to cycle through all users and their corresponding lists of integers; what's the best way to load and parse through this object?

Eventually I want to do something like:

for user, intlist in [FILE]:
    for item in intlist:
        [perform some function on each int]

though I'm not sure the right way to set up the IO and then leveraging the json library.

1

3 Answers 3

2

Just load the file with json.load():

import json

with open('yourfile') as infile:
    for user, intlist in json.load(infile).iteritems():
        for item in intlist:

Your JSON contains a dictionary top-level object, so the above code calls .iteritems() to loop over each key-value combo in that object.

Sign up to request clarification or add additional context in comments.

Comments

0

Something like this:

import json
with open('file.json', 'r') as f:
    data = json.load(f)
for user, intlist in data.items():
    for item in intlist:
        do_your_stuff(item)

Comments

0

Aside from the above answers, you may also try the package 'simplejson' which supports a bit more python objects than the plain 'json'

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.