Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get Value from Json by Key

I am having a json response as shown below

{
    "SNGS": {
        "$": {
            "xmlns": "csng",
            "xmlns:ns2": "http://www.w3.org/1999/xlink"
        },
        "Defect": [{
            "$": {
                "id": "DCV19294",
                "ns2:href": "https://mywebsite.com/api/beta//bug/DCSV19294"
            },
            "Field": [{
                "_": "4",
                "$": {
                    "name": "Severity"
                }
            }, {
                "_": "N",
                "$": {
                    "name": "Status"
                }
            }]
        }]
    }
}

I am trying to get value of below keys:
1] id
2] status

I tried to parse json & get value by key using below code but I am getting undefined in alert. WHY?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const data='{"SNGS":{"$":{"xmlns":"csng","xmlns:ns2":"http://www.w3.org/1999/xlink"},"Defect":[{"$":    {"id":"DCV19294","ns2:href":"https://mywebsite.com/api/beta//bug/DCSV19294"},"Field":[{"_":"4","$":{"name":"Severity"}},{"_":"N","$":{"name":"Status"}}]}]}}'

const parsedData = JSON.parse(data);

console.log(parsedData.id);
console.log(parsedData.Status);

I want to get id i.e.DCV19294 & status i.e. N from above Json. please help.

>Solution :

We don’t know the logic behind the extraction of data. You could access it directly like below. However there could be a better logic if you explain it a bit more.

const data='{"SNGS":{"$":{"xmlns":"csng","xmlns:ns2":"http://www.w3.org/1999/xlink"},"Defect":[{"$":    {"id":"DCV19294","ns2:href":"https://mywebsite.com/api/beta//bug/DCSV19294"},"Field":[{"_":"4","$":{"name":"Severity"}},{"_":"N","$":{"name":"Status"}}]}]}}'

const parsedData = JSON.parse(data);

const id = parsedData.SNGS.Defect[0].$.id
const name = parsedData.SNGS.Defect[0].Field[1]._

console.log(id, name)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading