PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

[FIXED] How to extract data from json?

 July 25, 2022     json, python, python-requests     No comments   

Issue

With following code I extract this output but how to extract the all ['_id'] from the output?

def geneinfo(gene):
    url = 'http://mygene.info/v3/query?q='+gene
    r = requests.get(url)
    return r.json()['hits']

geneinfo('cdk2')

The output:

[{'_id': '1017',
  '_score': 442.42224,
  'entrezgene': '1017',
  'name': 'cyclin dependent kinase 2',
  'symbol': 'CDK2',
  'taxid': 9606},
 {'_id': '12566',
  '_score': 371.0638,
  'entrezgene': '12566',
  'name': 'cyclin-dependent kinase 2',
  'symbol': 'Cdk2',
  'taxid': 10090},
 {'_id': '362817',
  '_score': 313.97708,
  'entrezgene': '362817',
  'name': 'cyclin dependent kinase 2',
  'symbol': 'Cdk2',
  'taxid': 10116},
 {'_id': '109992509',
  '_score': 285.43372,
  'entrezgene': '109992509',
  'name': 'cyclin-dependent kinase 2',
  'symbol': 'cdk2',
  'taxid': 56723},
 {'_id': '115358851',
  '_score': 285.43372,
  'entrezgene': '115358851',
  'name': 'cyclin-dependent kinase 2',
  'symbol': 'cdk2',
  'taxid': 586833},
 {'_id': '101675892',
  '_score': 285.43372,
  'entrezgene': '101675892',
  'name': 'cyclin dependent kinase 2',
  'symbol': 'CDK2',
  'taxid': 9669},
 {'_id': '105531943',
  '_score': 285.43372,
  'entrezgene': '105531943',
  'name': 'cyclin dependent kinase 2',
  'symbol': 'CDK2',
  'taxid': 9568},
 {'_id': 'ENSLCAG00010025960',
  '_score': 285.43372,
  'name': 'cyclin-dependent kinase 2',
  'symbol': 'cdk2',
  'taxid': 8187},
 {'_id': 'ENSLCAG00010026017',
  '_score': 285.43372,
  'name': 'cyclin-dependent kinase 2',
  'symbol': 'cdk2',
  'taxid': 8187},
 {'_id': 'ENSLOCG00000004109',
  '_score': 285.43372,
  'name': 'cyclin dependent kinase 2',
  'symbol': 'cdk2',
  'taxid': 7918}]

Solution

If data is your output from the question you can do:

out = [d["_id"] for d in data]
print(out)

Prints:

[
    "1017",
    "12566",
    "362817",
    "109992509",
    "115358851",
    "101675892",
    "105531943",
    "ENSLCAG00010025960",
    "ENSLCAG00010026017",
    "ENSLOCG00000004109",
]


Answered By - Andrej Kesely
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing