How to pass JSON value into a variable / function? - javascript

I am currently parsing a json file and appending the data to an HTML table. I need to create a few variables that equal 3 of the properties within my JSON object. And I need to include those variables in a function that I am appending to one of the td elements within the table for each of my JSON objects.
Here is my function to append the data...
function createPatientTable(json) {
$.each(json.LIST, function(i, COPD_QUAL) {
$('.footable > tbody:last').append('<tr><td>' + COPD_QUAL.PATIENT + '</td><td>' + COPD_QUAL.FIN + '</td><td>' + COPD_QUAL.NURSE_UNIT + '</td><td>' + COPD_QUAL.ROOM + '</td><td>' + COPD_QUAL.BED +'</td><td>' + COPD_QUAL.ATTENDING_PHYS + '</td><td>' + COPD_QUAL.LENGTH_OF_STAY + '</td><td class="assessment ' + getSeverity(COPD_QUAL.MED_ASSESS) + '" onclick="openPowerform">' + COPD_QUAL.MED_ASSESS + '</td></tr>');
});
$('.footable').footable();
};
Here is one of my JSON objects (formatted for readability):
{
"COPD_QUAL":15,
"LIST":[
{
"PATIENT": "TEST, TRICKLE",
"FIN": "70100905",
"NURSE_UNIT": "TIC",
"ROOM": "C219",
"BED": "A",
"ATTENDING_PHYS": "LEVITEN , DANIEL L",
"LENGTH_OF_STAY": "171days 02:14:15",
"MED_ASSESS": "Mild exacerbation",
"ACTIVITY_ID": "305675472.0000",
"PERSON_ID": 8986122.000000,
"ENCNTR_ID": 14150574.000000
}
]
}
I need to plug COPD_QUAL.PERSON_ID, COPD_QUAL.ENCNTR_ID, and COPD_QUAL.ACTIVITY_ID into my below function so when the td element is clicked, the below function triggers with the personid, encntrid, and activityid of the JSON object that has been appended to that row:
function openPowerform() {
var dPersonId = "COPD_QUAL.PERSON_ID";
var dEncounterId = "COPD_QUAL.ENCNTR_ID";
var formId = 0.0;
var activityId = "COPD_QUAL.ACTIVITY_ID";
var chartMode = 1;
var mpObj = window.external.DiscernObjectFactory("POWERFORM");
mpObj.OpenForm(dPersonId, dEncounterId, formId, activityId, chartMode);
};
How can I successfully make these variables "dynamically" equal my JSON values? (since the values are different per object/string within my JSON file).
Thanks in advance!

Your JSON is mal-formed. Here is a valid object:
{
"COPD_QUAL": 15,
"LIST": [
{
"PATIENT": "TEST, TRICKLE",
"FIN": "70100905",
"NURSE_UNIT": "TIC",
"ROOM": "C219",
"BED": "A",
"ATTENDING_PHYS": "LEVITEN , DANIEL L",
"LENGTH_OF_STAY": "171days 02:14:15",
"MED_ASSESS": "Mild exacerbation",
"ACTIVITY_ID": "305675472.0000",
"PERSON_ID": 8986122,
"ENCNTR_ID": 14150574
}
]
}
Each object within the LIST array has to be addressed by its array position. With this object, your object property references would be:
LIST[0].PERSON_ID, LIST[0].ENCNTR_ID, and LIST[0].ACTIVITY_ID
I don't know if this is how you want to structure your JSON in the end, but this is what you have now. Also, there is no absolute need to run this through JSON.parse(). It can be treated like a JavaScript Object Literal and accessed the same way.

Related

Array.push only pushing a single value instead of all of them in JS

I have declared a simple array in my JavaScript and I'm trying to push values from another array that has a dictionary inside it. But only the first value is getting pushed and not the rest of them.
<script>
complist = []
var testjs = [{'issuancedte': 'Finance', 'totalcomp': 1}, {'issuancedte': 'AnotherOne', 'totalcomp': 5}]
for (opt in testjs)
if ((adm_section_array.includes(testjs[opt].issuancedte)))
$('#data').append('<tr><td>' + testjs[opt].issuancedte + '</td><td>' + testjs[opt].totalcomp + '</td></tr>')
complist.push(testjs[opt].totalcomp);
</script>
So, from the code above I should be getting:
complist = [1, 5]
but instead I'm only getting:
complist = [1]
For some completely unknown reasons, if I place the .push line above the one where I'm appending data to a form, the complist is made as it should be but the table doesn't get appended.
This should be written like this,
if ((adm_section_array.includes(testjs[opt].issuancedte))) {
$('#data').append('<tr><td>' + testjs[opt].issuancedte + '</td><td>' + testjs[opt].totalcomp + '</td></tr>')
complist.push(testjs[opt].totalcomp);
}
Notice the curly braces after if block.

Return a field from a stringified object stored in localStorage

I have my JSON file like this:
{"companies":
[{"name":"LCBO", "City":"Mississauga", "Province":"Ontario",
"Website":"http://www.lcbo.com/content/lcbo/en.html#.WXtQ94jytPY",
"PhoneNumber":"1(800)668-5226",
"Longitude":"-79.381735", "Latitude":"43.648607"}]}
Here is my JavaScript to store the JSON file in local storage when the button is clicked:
$(document).ready(function() {
$('#btn1').click(function() {
$.ajax({
url:'company.json',
dataType:'json',
success: function(data) {
var u = data.companies[1];
$(u).each(function() {
$('#result1').append("<p>"+ "Company name: "+this.name + "<p>" +
"<p>"+ "City: " +this.City + "<p>" +
"<p>"+ "Province: "+this.Province + "<p>" +
"<p>"+ "Website: " +this.Website + "<p>" +
"<p>"+"Phone Number: "+this.PhoneNumber + "<p>" +
"<p>"+"Longitude: "+this.Longitude + "<p>" +
"<p>"+"Latitude: "+this.Latitude + "<p>");
saveData(u);
});
}
});
function saveData(data) {
var obj = {"Value":data};
if (window.localStorage) {
alert("Local Storage is supported");
localStorage.setItem("Information", JSON.stringify(obj));
} else {
alert("Local Storage is not supported");
}
}
});
The question is that how I get the value "Longitude" and "Latitude" from the local storage.
var info = JSON.parse(localStorage.getItem('Information'));
that way you'll get object stored in localStorage as a JSON object you can iterate through to get the values you want
You need to get the "Information" from localStorage, which will be a JSON string, parse it back into a javascrpt object, look in the "Value" property you created for the companies array and get an array element containing one company's data (the 0th is the first company returned from ajax), and then extract the Latitude (or Longiture) property.
JSON.parse(window.localStorage.get("Information")).Value.companies[0].Latitude
If this seems overly complicated, you can do it in steps:
var info = window.localStorage.get("Information");
var obj = JSON.parse(info);
var companies = obj.Value.companies;
var myCompany = companies[0];
var lat = myCompany.Latitute;
Also, perhaps simplify the data after ajax fetching instead of embedding it in another object. Also, the current structure will only cache the last-retrieved ajax query. To store multiple queries in localStorage requires either having a key for each company or pulling out the old object, updating it, and putting it back in localStorage. There is a limit as to what is practical to store locally.

How can I retrieve the JSON Object Array Value using JavaScript

My JSON Object Array is something like this:
var country = [{ id: "1", name:"ajith", country:"india"},
{ id: "2", name:"chandru", country:"india"},
{ id: "3", name:"gane", country:"india"}]
How can I retrieve these key and values?
And how can I display them in an html table?
Like so, just replace <tableIdHere> with your table's id
document.getElementById('<tableIdHere>').getElementsByTagName('tbody')[0].innerHTML =
country.map(v => `<tr><td>${v.id}</td><td>${v.name}</td><td>${v.country}</td></tr>`)
.join('');
Please note that arrow functions and template strings as used above are only available in modern browsers like latest chrome and firefox. You might want to use
document.getElementById('<tableIdHere>').getElementsByTagName('tbody')[0].innerHTML =
country.map(function(v) {
return '<tr><td>' + v.id + '</td><td>' + v.name + '</td><td>' + v.country + '</td></tr>';
}).join('');
if you need support for older browsers!

Parse JSON with JavaScript to build a HTML string

I currently have built an API which posts JSON strings of objects. A simple example of the JSON is:
[ {
"id" : 0,
"name" : "test SAMPLE Att1 name",
"attributes" : [ {
"id" : -1,
"name" : "AttKey1",
"value" : "AttValue1"
}, {
"id" : -1,
"name" : "AttKey2",
"value" : "AttValue2"
} ]
} ]
My issue lies in my client code here:
function loadSamples() {
$("#content").children().remove();
$.getJSON("/api/samples", function (data) {
$.each(data, function (key, val) {
$("<tr><td>" + val.id + "</td><td>" + val.name + "</td><td>" + val.attributes + "</td>" +
"</tr>").appendTo("#content");
});
initCallbacks();
});
}
I am iterating through each sample I send (in this case only one, and appending the field values to the HTML string. How can I iterate through attributes and append each attribute.key and attribute.value to the string?
A picture of the current problem:
You can try to use this code instead of val.attributes
$.map(val.attributes, function(item){
return item.key + ':' +item.value;
}).join(',')
Use another loop, iterate through all attributes, build an array of attributes in format "property: value" and then append joined array to HTML:
$.each(data, function (key, val) {
var attributes = [];
for (var prop in val.attributes) {
var value = val.attributes[prop];
attributes.push(prop + ": " + value);
}
$("<tr><td>" + val.id + "</td><td>" + val.name +
"</td><td>" + attributes.join(",") + "</td>" + "</tr>").appendTo("#content");
});
If you feel nerdy you can just serialize the object back into a JSON string like this:
... + JSON.stringify(val.attributes) + ...
It is recursive, has a standard syntax (JSON) and doesn't require any support function or additional code at all.

jQuery each() breaking on null

I have a JSON object that I am looping over with each() to add table rows to a table. I can't ensure the completeness of the data presented in the JSON arrays and I occasionally run into some NULLs.
For instance:
// A GOOD ARRAY
{
id: "193",
location: {
city: "Atlanta",
state: "GA"
},
name: "John"
},
// NOW WE STUMBLE UPON A BAD ARRAY WITH A NULL
{
id: "194",
location: {
city: "Boise",
state: null
},
name: "Frank"
},
{...}
Now, when I am dealing with JSON objects that have no NULL values, the each() loops over with no problems. As soon as I encounter a member with NULL anywhere in the array, the looping breaks.
This is how I am looping over this:
$.getJSON("/getstuff/jsonprovider.php", function (data) {
var results = data.parentnode;
var tableThing = $(".myTable tbody");
var i = 0;
$.each(results, function () {
tableThing.append('<tr><td></td><td>' + results[i].id + '</td><td>' + results[i].name + '</td><td>' + results[i].location.city + ', ' + results[i].location.state + '</td></tr>');
i++;
});
});
Should I be investigating something other than each() here, or should I be using a completely different method?
Thank you
Since your data may have nulls, you need to make sure that the data exists before you attempt to use it. It is also more efficient to only use .append once. Below i'm using a default empty object and $.extend deep copy to ensure that the object we are pulling data from always has all data values defined, even if the value isn't in the json. I'm still not sure how null's will be handled at this point.
var emptyObj = {
id: "",
name: "",
location: {
city: "",
state: ""
}
},htmlToAppend = "";
$.each(results, function (i,obj) {
var newObj = $.extend(true,{},emptyObj,obj);
htmlToAppend += '<tr><td></td><td>' + newObj.id + '</td><td>' + newObj.name + '</td><td>' + newObj.location.city + ', ' + newObj.location.state + '</td></tr>';
});
tableThing.append(htmlToAppend);
The proper way to do a $.each is like this:
var myObj = {...};
$.each(myObj, function(k, v){
//..
});
You need two parameters above:
k holds the index or the key
v holds the value at that index or key
If you were going to use a counter variable like i you might as well use JavaScripts for in loop:
for(var i in myObj){
//..
}

Categories

Resources