Reputation: 397
I have nested JSON data which I am trying to parse using Javascript:
[
{
"fullUrl": "https://replacedURL.org/v/r4/fhir/MedicationRequest/83b6c511-8b78-4fe2-b484-346ddee61933",
"resource": {
"resourceType": "MedicationRequest",
"id": "83b6c511-8b78-4fe2-b484-346ddee61933",
"meta": {
"versionId": "4",
"lastUpdated": "2021-04-06T03:14:44.834-04:00",
"tag": [
{
"system": "https://smarthealthit.org/tags",
"code": "synthea-5-2019"
}
]
},
"status": "active",
"intent": "order",
"medicationCodeableConcept": {
"coding": [
{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": "316049",
"display": "Hydrochlorothiazide 25 MG"
}
],
"text": "Hydrochlorothiazide 25 MG"
},
"subject": {
"reference": "Patient/2cda5aad-e409-4070-9a15-e1c35c46ed5a"
},
How do I parse and print the names all of the medications into a div element with id="meds" under the JSON key "text"? What I am trying which is incomplete:
for (var i = 0; i < prop.length; i++) {
if(typeof obj[prop[i]] == 'undefined')
return defval;
obj = obj[prop[i]];
document.getElementById("meds").innerText = obj ++ ;
}
Not entirely sure what do to here. Help please?
Upvotes: 0
Views: 569
Reputation: 19301
Steps to populate the DIV element with a list of medications include
Implementing step 1 depends on the choice of communication API used on the frontend (e.g. fetch
, axios
or jQuery
) or if the JSON string is hardcoded in a script element inserted into page HTML when serving the page.
Step 2 may be included in step 1 by some APIs automatically, based on the mime type of response content, or by executing some kind of json
method on the response object. If the front end gets the JSON as a text string it can call JSON.parse
to convert the text into an object.
Step 3 doesn't appear to need parsing - the text
property is of a nested object in an array entry. Standard shortcut notation to access its value may suffice. For example:
// assume dataArray is the result of parsing the JSON text.
// assume "meds" is the id of a DIV element
function listMeds( dataArray) {
const div = document.getElementById("meds");
dataArray
.map(entry => entry.resource.medicationCodeableConcept.text)
.map( med=> {
const span = document.createElement("span");
span.textContent = med;
const br = document.createElement("br");
div.appendChild(span);
div.appendChild( br);
})
}
Upvotes: 2