nikiforosb
nikiforosb

Reputation: 23

Reading a nested json file

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

Answers (2)

Daniel Roseman
Daniel Roseman

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

Underyx
Underyx

Reputation: 1679

You can just extract all the keys from the dicts within your j variable with the .keys() method, as such:

men = j['men_rankings'].keys()
women = j['women_rankings'].keys()

Upvotes: 1

Related Questions