-1

I've a json file in the following format

{
"project1": {
    "alias1": {
      "command":"somecommand for alias1"
    }
  },
"project2": {
    "alias2": {
      "command":"somecommand for alias2"
    },
    "alias3": {
      "command":"somecommand for alias3"
    }
 }

I want to extract the data and print the output as a Dict in the following format

{
'alias1':'command', # Command for alias1
'alias2':'command', # Command for alias2
'alias3':'command'  # Command for alias3
}

How can I achieve this in python2 ?

Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59
  • 3
    Possible duplicate of [Parsing values from a JSON file using Python?](http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-using-python) – McGrady Apr 11 '17 at 10:12
  • @McGrady: Not really. In my case i am looking for printing the top level key and its child's value – Mridhul Pax Apr 11 '17 at 10:36
  • It's still a dupe IMO. You want to parse the JSON; What you want to do with it afterwards is irrelevant. Particularly as you have not shown that you have made any effort to solve this yourself. – SiHa Apr 11 '17 at 10:56

4 Answers4

1

Firstly there's an error in your source JSON, it needs a closing "}"

After fixing that you can use json.loads to get it into a Python variable, and then run over it with Python loops and conditionals to extract what you want. Something like

ss = json.loads( """ # JSON source as above
                     # etc
    """)
res = {}
for proj,v in ss.items():
    for alias,d in v.items():
        if alias.startswith("alias"):
            res[alias] = d["command"]

res is the dict you want, and you can print it using json.dumps and (probably) indent=0 and sort_keys=True

nigel222
  • 7,582
  • 1
  • 14
  • 22
  • I there any advantage of using json over ordinary python dictionaries in this case? (the error in JSON was what I noticed first - strange the others haven't mentioned it ...) – Claudio Apr 11 '17 at 11:41
  • If it *is* JSON from an application you do not control, you cannot safely rely on it being consistently pretty-printed, or staying so at all future times. You need a full JSON parse to be sure it is correctly processed. – nigel222 Apr 11 '17 at 12:13
0

Not sure if this is what you were looking for:

result = {value:v for key in a for value in a[key] for item in a[key][value] for k,v in a[key][value].items()}

{'alias2': 'somecommand for alias2',
'alias3': 'somecommand for alias3',
'alias1': 'somecommand for alias1'}
zipa
  • 27,316
  • 6
  • 40
  • 58
0

you can try like this

def dict_parse(dict):
     dict_new = {}
     keys = dict.keys()
     for k in keys:
          key_new = dict[k].keys()
          for i in key_new:
               dict_new[i] = dict[k][i]
     return dict_new

output will be this :

 {'alias1': {'command': 'somecommand for alias1'},
 'alias2': {'command': 'somecommand for alias2'},
 'alias3': {'command': 'somecommand for alias3'}}

i think you should try this based on this you can get your exact output

Atul Jain
  • 1,053
  • 11
  • 36
0

you can use this

print({i:j['command'] for k,v in df.items() for i,j in v.items() if i.startswith('alias')})
zhe
  • 1