How to parse nested JSON data using Javascript efficiently? - javascript

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?

Steps to populate the DIV element with a list of medications include
Obtain the JSON text which encodes the data object.
Parse the JSON (text) to create a JavaScript Object value
Use the object obtained to list medications in a DIV element.
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);
})
}

Related

How to extract data from an object API response Apps script goole sheets

//I want to achieve "highestBid": "94628.41" displayed in A3 cell - the value of highestBid varies with time.
function response() {
var url = "https://api.zonda.exchange/rest/trading/ticker/BTC-PLN";
var response = UrlFetchApp.fetch("https://api.zonda.exchange/rest/trading/ticker/BTC-PLN");
var obj = { highestBid: "94628.41" };
type: "Fixed Multiple";
Status: "Active";
var result = Object.keys(obj).map((key) => [key, obj[key]]);
Logger.log(result);
SpreadsheetApp.getActiveSheet().getRange("A3").setValue(result);
}
The most important thing for you to do is to get the response body as a string using getContentText() and parse it as JSON using JSON.parse() so you can access the values easily in JavaScript following the structure of the returned data:
{
"status": "Ok",
"ticker": {
"market": {
"code": "BTC-PLN",
"first": { "currency": "BTC", "minOffer": "0.0000468", "scale": 8 },
"second": { "currency": "PLN", "minOffer": "5", "scale": 2 },
"amountPrecision": 8,
"pricePrecision": 2,
"ratePrecision": 2
},
"time": "1663191022379",
"highestBid": "94563.2",
"lowestAsk": "94846.78",
"rate": "94846.78",
"previousRate": "94566.21"
}
}
You should also make some other changes:
use const instead of var to treat values as immutable and you might also be interested in their scope
you should check for the response code using getResponseCode() as if the request fails (which it can for many reasons) you won't be able to access the data or get unexpected data returned. See HTTP status codes - Wikipedia.
For more details on what parsing means and how JSON and JavaScript are connected see this explanation.
Here now how you can set the value of highestBid in cell A3.
function response() {
const url = "https://api.zonda.exchange/rest/trading/ticker/BTC-PLN";
const response = UrlFetchApp.fetch(url);
if(response.getResponseCode != 200){
Logger.log(`The request failed with status code ${response.getResponseCode()}`)
} else {
// get the content of the response body as string (in UTF-8 encoding)
const responseStr = response.getContentText("UTF-8")
// the string is in JSON format so we can now parse it to make it accessible in javascript
const data = JSON.parse(responseStr);
// the hightest bid can now easily be obtained
const highestBid = data.ticker.highestBid;
Logger.log(`The highest bid is ${highestBid} until ${new Date(data.ticker.time).toLocaleString()}`)
// set value in cell A3
SpreadsheetApp.getActiveSheet().getRange("A3").setValue(highestBid);
}
}
By the way: Object.entries(result) returns the same result as var result = Object.keys(obj).map((key) => [key, obj[key]]);.

How to convert JSON property array to Array of strings Object in node.js?

I currently have the following JSON:
{
"Id": ["1", "2"],
"Settings": [{ "Key": "IgnitionOn", "Value": "true" }]
}
I want to be able to access Id and convert it to an Array of strings in node.js. Namely, what I want to do is access Id using req.body.Id. This works when Id is just a string. If I try to access req.body.Id currently, I get it to be undefined. I have also tried JSON.parse(req.body.Id) and JSON.stringify(req.body.Id) but in both approaches, the Ids are still undefined. Given my req body above, any suggestions on how I can create an instance of an array that is precisely the Id array in the body?
Any help will be much appreciated!
You can parse this JSON to get an object:
const result = JSON.pasrse(req.body)
const id = result.id;
If you body is in JSON, you will need to parse then entire body with JSON.parse(req.body) before accessing the .Id field
let req = {
body: `{
"Id": ["1","2"],
"Settings": [{"Key": "IgnitionOn", "Value": "true"}]
}`
}
let body = JSON.parse(req.body)
let ids = body.Id
console.log(ids)
// [ '1', '2' ]

Grabbing a specific value from a response

I am trying to set a postman environment variable based on a specific value in a response.
I'm unsure on code to use use to grab value.
I know I need to set the response as a variable which I have done as follows:
var response = JSON.parse(responseBody);
And I know I can use the following to set my environment variable:
postman.setEnvironmentVariable("category_ref",myVariableName);
Below is a snippet from my response:
{
"id": 45,
"name": "Accommodation",
"description": ""
},
{
"id": 46,
"name": "Accommodation (Engineering)",
"description": ""
},
I want to grab the "id" value based on "name" value which I will already know.
So an example being I want my code to give me the ID where "name" = "Accommodation"
Edit:
Changed made to original question following answers below.
My Tests code now looks like this:
//Ensure the API Test Category is present
var response = JSON.parse(responseBody);
tests["my test"] = responseBody.has("Accommodation");
//pass in id into variable for delete step
var requiredId = pm.response.json().find(function(element){
if (element.name == "Accommodation"){
return element.id;
}
});
stringId = JSON.stringify(requiredId);
pm.environment.set("category_ref",stringId);
console.log("my string "+stringId);
And my output to console looks like the following which is also the value that is being sent to the category_ref environment variable:
my string {"id":45,"name":"Accommodation","description":""}
The remaining problem is I don't want to return all the elements as it is doing above, I am wanting to return just "45" which is the id value where name = Accommodation.
Tests in Postman are noting but the JavaScript, so you can use Array.find() as follows,
Response Body:
[
{
"id": 45,
"name": "Accommodation",
"description": null
},
{
"id": 46,
"name": "Accommodation (Engineering)",
"description": null
}
]
Test window:
var matchedItem = pm.response.json().find(function(element) {
if (element.name == "Accommodation") {
return element;
}
});
console.log(matchedItem.id);

Extract data from API Object in React

I'm trying to retrieve data from an API with the following JSON output and I have a function in react that I call.
I can see the api output in console.log(users) so the data is being passed into the function.
I am trying to output the array contained in "data" but can't seem to access the data.
{
"dataCount": 2,
"data": [
{
"name": "Test review header",
"text": "This is adescription for a test review",
"img": "http://pngimg.com/upload/pigeon_PNG3423.png"
},
{
"name": "Test review header2",
"text": "This is adescription for a test review2",
"img": "http://pngimg.com/upload/pigeon_PNG3422.png"
}
]
}
renderUsers() {
const { users } = this.props;
console.log(users);
Object.keys(users).map(name => users[name])
console.log(users[name]);
};
The data you need to iterate over is present in the data field of users.
When you are using lists you have to specify the key property, to make react keep track of each item in list.
renderUsers() {
const { users } = this.props;
return (
<ul>
{
users.data.map(name => {
<li key={name}>users[name]</li>
})
}
</ul>
)
}
First of all, I don't use react but what you want should be the same in other javascript frameworks.
Are you sure that it is JSON you receive?
We need to be sure that you receive a JSON object and not normal text. Lets say you have a function parseResponse(data). We can call JSON.parse(data) to parse the data param to a json object. It is also possible that you store the result in a variable.
Using the JSON object
When we are sure you have the param parsed to a JSON object, we get it's data. For example, if you want to get the name of the first object in data, you can call:
parsedJson.data[0].name
where parsedJson is the result of JSON.parse(data),
data is an array of objects in the JSON,
0 is the first object in the array
It is possible that you have this kind of function then:
function parseResponse(data) {
var parsedJson = JSON.parse(data);
for(var i = 0; i < parsedJson.data.length; i++) {
console.log(parsedJson.data[i].name);
}
}
see jsfiddle

json comes in as object not string

Json is sitting on my localhost as: /data/:
{
"children": [
{
"name": "analytics",
"size": "1243"
},
{
"name": "math",
"size": "4343"
},
{
"name": "algebra",
"size": "1936"
},
{
"name": "calc",
"size": "3936"
},
{
"name": "geom",
"size": "2136"
},
{
"name": "Quant",
"size": "4136"
}
]
}
Here is how I am trying to access the json:
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,name){
alert(json.children);
});
});
}, 3000);
The data comes in just fine. That is, when I run console.log(json) I can see the above json name/value txt pairs in firebug. However, before each name value pair I see the word Object. So for example instead of my log showing { name="analytics", size="1243"},.. it actually shows: [Object { name="analytics", size="1243"},... And that too is what my alert shows: [object Object] instead of name="analytics", size="1243".
Why is this and is there a way to get my json name/value pairs in text so that I can store as a javascript String?
Many thanks in advance.
jQuery does automatically decode the response when using jQuery.getJSON or specifying the response as JSON. If you want the plain response, use jQuery.ajax instead.
The O in JSON stands for "object." It's a way of serializing a JavaScript object to a string (and back). You seem to be relying on the conversion on one hand (referencing children) but not want to have the conversion done on the other hand. If you really want children to be a collection of strings in the format you describe, you should store it that way. If you really do want the object notation (and conversion to objects in the client), then you can simply use the properties of the object.
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,item){
alert("name = " + item.name + ", size = " + item.size);
});
});
}, 3000);
Everything you've stated is normal behavior for both firebug and alert. You can't alert an object.
Here's example of how to loop the response within your $.get callback
http://jsfiddle.net/Y3N4S/
$.each(json.children, function(i, item){
$('body').append('<p>Name: '+item.name+' , Size: '+item.size+'</p>')
})
Well, working with Objects is the intend of "Javascript Object Notation".
Actually, your json is an Array of Objects.
{
"children": [ // <-- Array
{...},// <- Object
{...} // <- Object
]
}
You can access your key-value pairs this way: children[0].name
for (var i=0;i< children.length; ++){
console.log( children[i].name);
console.log( children[i].size);
}

Categories

Resources