Skip to content
Advertisement

How can I extract specific value from JSON response?

Hi I am trying to get value from JSON response which Im getting from GitLab API. Code should extract “commiter_name” value but it does not work, already tried several options from internet.

def getCom():

      com = requests.get("https://gitlab.com/api/v4/projects/.."
      
      headers = {'PRIVATE-TOKEN': '.....'}).content

Error:

File "getData.py", line 24, in getCom resp = com.json() ["commiter_name"]
AttributeError: 'bytes' object has no attribute 'json'

Advertisement

Answer

This is because you did not include you api token in the header. Also please check that the website you are pointing to in the request ends in commits.

Do this,

headers = {'PRIVATE-TOKEN': 'Your API key here!'}
com = requests.get('https://gitlab.example.com/api/v4/projects/5/repository/commits', headers=headers)
print(com.json())

You can also try this with the output you got,

print(json.loads(com.decode('utf-8')))

Your output should be a list of json data. You will be able to access it using a for loop to go through the list and finding your committer_name. For example if it was the first item in the json file.

com.json()[0]["commiter_name"]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement