Reputation: 23
I have a JSON file like this:
{
"men_rankings": {
"abe": ["cat", "bea", "ada"],
"bob": ["ada", "cat", "bea"],
"cal": ["ada", "bea", "cat"]
},
"women_rankings": {
"ada": ["abe", "cal", "bob"],
"bea": ["bob", "abe", "cal"],
"cat": ["cal", "abe", "bob"]
}
}
and I want to save in two lists the men's and women's names (I am working in python). (I just want this: mens = ['abe', 'cal', 'bob']
). An other user may give totally different names so I have to find a way to save the names without knowing for example that men's names are abe, cal, bob. If I use this way:
import json
import sys
f = open(sys.argv[2], 'r')
j = json.load(f)
f.close()
in variable j
there will be all the contents of the file without knowing what the names are. Have you any idea?
Thanks in advance!
Upvotes: 0
Views: 87
Reputation: 599470
You don't need to know the names. json.loads()
converts this to a Python data structure, in this case nested dicts. Dicts have a keys()
method that gives the keys. So:
mens = j['men_rankings'].keys()
womens = j['women_rankings'].keys()
Upvotes: 2