user9399405
user9399405

Reputation:

Parsing out specific values from JSON object in BeautifulSoup

import urllib
from urllib import request
from bs4 import BeautifulSoup

url = 'http://mygene.info/v3/query?q=symbol:CDK2&species:human&fields=name,symbol,entrezgene'
html = request.urlopen(url).read()
soup = BeautifulSoup(html)

Output:

<html><body><p>{
  "max_score": 88.84169,
  "took": 6,
  "total": 244,
  "hits": [
    {
      "_id": "1017",
      "_score": 88.84169,
      "entrezgene": "1017",
      "name": "cyclin dependent kinase 2",
      "symbol": "CDK2"
    },
    {
      "_id": "12566",
      "_score": 73.8155,
      "entrezgene": "12566",
      "name": "cyclin-dependent kinase 2",
      "symbol": "Cdk2"
    },
    {
      "_id": "362817",
      "_score": 62.09322,
      "entrezgene": "362817",
      "name": "cyclin dependent kinase 2",
      "symbol": "Cdk2"
    }
  ]
}</p></body></html>

Goal: From this output, I would like to parse out the entrezgene, name, and symbol values

Question: How do I go about accomplishing this?

Background: I have tried https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class and Python BeautifulSoup extract text between element to name a couple but I am not able to find what I am looking for

Upvotes: 17

Views: 40583

Answers (1)

Bitto
Bitto

Reputation: 8215

You can get the text which is in json format. Then use json.loads() to convert it to a Dictionary.

from urllib import request
from bs4 import BeautifulSoup
import json
url = 'http://mygene.info/v3/query?q=symbol:CDK2&species:human&fields=name,symbol,entrezgene'
html = request.urlopen(url).read()
soup = BeautifulSoup(html,'html.parser')
site_json=json.loads(soup.text)
#printing for entrezgene, do the same for name and symbol
print([d.get('entrezgene') for d in site_json['hits'] if d.get('entrezgene')])

Output:

['1017', '12566', '362817', '100117828', '109992509', '100981695', '100925631']

Upvotes: 29

Related Questions