简体   繁体   中英

How to get specific data from a dictionary in python

So I have a json file. Where I load it as json file in python and I try to get the items from the dictionary. I can access the 'sha' the 'author' and get all of its components but how can I access just the 'message', 'name', and 'date' ?

I try this code to access the 'messages' but I get a key error:

    data = json.load(json_file)
    print(str(type(data))) # class <dict>
    for p in data['commits']:
        print(p['message'])

My file Looks like this: (It contains more than one commit messages):

{

   "commits":[  
      {  
         "sha":"exampleSHA",
         "node_id":"exampleID",
         "commit":{  
            "author":{  
               "name":"example",
               "email":"example@example.se",
               "date":"2015-09-07T22:06:51Z"
            },
            "committer":{  
               "name":"example",
               "email":"example@example.se",
               "date":"2015-09-07T22:06:51Z"
            },
            "message":"Added LaTex template and instructions",
            "tree":{  
               "sha":"examplesha",
               "url":"http://example.url"
            },
         "parents":[]
      }}
   ]
}

There are many 'messages' that I want to get all of them from the dict.

The result would be this:

AuthorName   Message                                Date
example      Added LaTex template and instructions  2013-07-08T20:16:51Z
example2     Message2                               2015-09-07T22:06:51Z
....         ....                                   .....

Try this :

data = json.load(json_file)
print(str(type(data))) # class <dict>
for p in data['commits']:
    print(p['commit']['message'])

message field is nested inside commit field.

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