Search code examples
javascriptjsonpubmed

How to extract a particular value from this json output


I am trying to decode pubmed json output as follows.

  1. https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=29753496&retmode=json

  2. https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=15674886&retmode=json

How can I extract the doi from this output?

        "articleids": [
            {
                "idtype": "pubmed",
                "idtypen": 1,
                "value": "15674886"
            },
            {
                "idtype": "doi",
                "idtypen": 3,
                "value": "10.1002/14651858.CD001801.pub2"
            },
            {
                "idtype": "rid",
                "idtypen": 8,
                "value": "15674886"
            },
            {
                "idtype": "eid",
                "idtypen": 8,
                "value": "15674886"
            }
        ],

I was able to extract other details like title, author name etc. But this one seems little tricky.

Sorry if its a silly question.


Solution

  • So, lets assume this is your whole JSON string.

    var json = '{"articleids": [
        { "idtype": "pubmed", "idtypen": 1, "value": "15674886" },
        { "idtype": "doi", "idtypen": 3, "value": "10.1002/14651858.CD001801.pub2" },
        { "idtype": "rid", "idtypen": 8, "value": "15674886" },
        { "idtype": "eid", "idtypen": 8, "value": "15674886" }
    ]}';
    

    Now we want to parse this and get it into an object.

    var arr = JSON.parse(json);
    

    To get a specific object based on the value of an item, we will want to use .filter(). We'll use .pop() to return the first element of the returned array, which in this case should be the only object returned.

    var doi = arr.articleids.filter(function(v)
    {
        return v.idtype == "doi";
    }).pop();
    

    Variable doi is now going to hold the filtered object.

    idtype: "doi"
    idtypen: 3
    value: "10.1002/14651858.CD001801.pub2"