简体   繁体   中英

reading json file python

js = {"Alex":{"b_":{"ep_0":"[1,2,3]"}, "g_":{"ep_0":"[3,4,5]"}, "f_":{"ep_0":"[3,4,5]", "ep_1":"[3,4,5]"}},
      "Sam":{"b_":{"ep_0":"[1,2,3]"}, "g_":{"ep_0":"[3,4,5]"}},
      "Joe":{"b_":{"ep_0":"[1,2,3]"}, "g_":{"ep_0":"[3,4,5]"}, "f_":{"ep_1":"[31,44,56]"}}
      }

I need to read ep_0 and ep_1 for each user, here is my snipped code:

users = [i for i in js.keys()]
data = {}
final_data = {}
for key in users:
        for user in js[key].keys():
            if 'f_' not in key:
                continue
            for z in js[users]['f_']:
                if 'ep_0' not in z:
                    continue
                data['ep0'] = js[user]['f_']['ep_0']
                if 'ep_1' not in z:
                    continue
                data['ep1'] = js[user]['f_']['ep_1']
                final_data[user] = data

    print(final_data)

the output of my code is {} and desire output should be:

{'Alex': {'f_':{'ep_0':'[3,4,5]', 'ep_1':'[3,4,5]'}}, 'Joe': { 'f_':{'ep_1':'[31,44,56]'}} }

Here is my simple solution to your problem.

final_data = {}
for user in js.keys():
    if 'f_' not in js[user]:
        continue
    final_data[user] = { "f_": js[user]['f_']}

print(final_data)

Output

{'Alex': {'f_': {'ep_0': '[3,4,5]', 'ep_1': '[3,4,5]'}}, 'Joe': {'f_': {'ep_1': '[31,44,56]'}}}

I think that your most glaring problem is

users = [i for i in js.keys()]
...
        for z in js[users]['f_']:

users is a poorly-formed list of the keys in your dict. Just what do you expect js[users] to mean?

However, your first problem is the combination

for key in users:
    for user in js[key].keys():
        if 'f_' not in key:

users is the list of names: Alex, Sam, Joe. How do you expect to find f_ in that list? You've incorrectly connected your variables.


I strongly recommend that you start over with your coding. Employ incremental programming . Write a couple of lines that do one step of your process. Insert print statements to test that they do what you expect. Only after you've proved that, do you add more lines.

The problem you're facing here is that you wrote too much code at once, making several mistakes, and you're now in a situation where a single fix cannot get you any reasonable output.

Been there, done that, and I have all too many t-shirts from my forays into my own creations.

I'm seeing js[users] in a few places in your code. You probably mean js[user] , since users is just the list of keys from js , not a key itself. Try fixing that and see if it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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