I have the following code
import requests
import json
parameters = {
"affiliation": "cambridge university"
}
response= requests.get("https://api.ror.org/organizations", params=parameters)
print (response.json())
This returns me JSON object that contains an array of items - this is the link to the result in API as its very long to paste it all here
The first result in the set has a value of ‘True’. From this result I want to pass the ‘name’ and the ‘aliases’ and ‘labels’ for the ‘child’ elements.
Based on the response from the API, I want to pass something like the following for the first result which is marked as "chosen":true:
"name":"University of Cambridge"
"aliases":["Cambridge University"]
"label":"Cambridge University Press","type":"Child"
"label":"Cambridge–MIT Institute","type":"Child"
etc. including each of the "type":"Child" relationships
I’m completely lost trying to do this. I’ve tried different things but the best I can get is ‘None’. How do I move through the array, using the ‘True’ criterion and get the relevant results?
CodePudding user response:
I hope I've understood your question right. To filter the result you can use next example:
import json
import requests
parameters = {"affiliation": "cambridge university"}
response = requests.get("https://api.ror.org/organizations", params=parameters)
result = []
for item in response.json()["items"]:
if item["chosen"] == True:
d = {"name": item["organization"]["name"]}
d["aliases"] = item["organization"]["aliases"]
d["labels"] = []
for r in item["organization"]["relationships"]:
if r["type"] == "Child":
d["labels"].append(r)
del r["id"]
result.append(d)
print(result)
Prints:
[
{
"name": "University of Cambridge",
"aliases": ["Cambridge University"],
"labels": [
{"label": "Cambridge University Press", "type": "Child"},
{"label": "Cambridge–MIT Institute", "type": "Child"},
{"label": "Cancer Research UK Cambridge Center", "type": "Child"},
{
"label": "Centre for the Observation and Modelling of Earthquakes, Volcanoes and Tectonics",
"type": "Child",
},
{"label": "Hutchison/MRC Research Centre", "type": "Child"},
{"label": "MRC Biostatistics Unit", "type": "Child"},
{"label": "MRC Cognition and Brain Sciences Unit", "type": "Child"},
{"label": "MRC Epidemiology Unit", "type": "Child"},
{"label": "MRC Human Nutrition Research", "type": "Child"},
{"label": "MRC Mitochondrial Biology Unit", "type": "Child"},
{"label": "MRC Toxicology Unit", "type": "Child"},
{"label": "Sedgwick Museum of Earth Sciences", "type": "Child"},
{
"label": "The Cambridge Centre for Advanced Research and Education in Singapore",
"type": "Child",
},
{
"label": "Wellcome/Cancer Research UK Gurdon Institute",
"type": "Child",
},
{
"label": "Wellcome/MRC Cambridge Stem Cell Institute",
"type": "Child",
},
{
"label": "Wellcome/MRC Institute of Metabolic Science",
"type": "Child",
},
],
}
]
EDIT: deleted id
key