How can I retrieve the JSON Object Array Value using JavaScript - 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!

Related

How to separate a JSON.stringify result

Related Retrieve two lists, sort and compare values, then display all the results
The question in the related post was how to combine two lists and sort them. The code referenced each item on each list. So, when I got the result, I could manipulate it.
The best solution used console.log(JSON.stringify(result,null,2)); to return the result, nicely combined and sorted.
Trouble for me is being able to translate that back into something I can work with. I can get the result into a variable and display it on the page, but it's the raw output : [ { "Title": "apple", "Type": "rome", "State": null }, ...
Have tried 'JSON.parse(result);' where result is the variable that is used to handle the combination and sorting of the two lists. All that gives is an invalid character error on the line. Also looked at the 'replace' option. That just confused me, tmi. Tried setting a variable directly on the result (so those who know are laughing) 'var foo = result;' That returns object, object.
The desired end result would be to end up with each item separate so I can put them in a table (or a list) on my html page with blanks in any column where there is no data.
I know there has to be a simple, easy way to do this without 200 lines of transformation code. But I can't find a clear example. Everything I'm seeing is for +experts or uses a super simple array that's typed into the code.
Is there a way to attach something like this (from my original) to the result instead of using JSON.stringify? What other step(s) am I missing in being able to extract the fields from JSON.stringify using JSON.parse?
}).success(function (data) {
var title = '';
var type = '';
$.each(data.d.results,
function (key, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
$("#tdtitle").html(title);
$("#tdtype").html(type);
Terry, you wrote: "All that gives is an invalid character error on the line"? Then result is not a valid json. Test it here: http://jsonlint.com/, fix it, then try again.
var data = {
d:{
results: [
{ "Title": "apple", "Type": "rome", "State": null },
{ "Title": "grape", "Type": "fruit", "State": null }
]
}
};
var title = '';
var type = '';
$.each(data.d.results, function (index, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
alert(title + type);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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.

How to pass JSON value into a variable / function?

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.

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){
//..
}

displaying json data in javascript not working

I have created a var and passed JSON data(comma seperated values) to it, but when I want to display json data - it only returns null. Here's the code:
<script type="text/javascript">
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
document.write(data1);
</script>
You can either do it like this:
var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];
data1.forEach(function(data){
document.write(data.order);
document.write(data.country);
document.write(data.employee);
document.write(data.customer);
});
or you can do it like this
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
$.each(data1[0], function(key, value){
document.write(key + " " + value);
});
Either way, storing just one object in the list makes this answer a bit redundant unless I show you how to loop over multiple objects.
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
data1.forEach(function(data){
$.each(data, function(key, value){
document.write(key+" "+value);
});
});
I'm using a mix of jQuery here aswell, which might not be optimal but atleast it serves to show that there are multiple ways to accomplishing what you need.
Also, the forEach() method on arrays is a MDN developed method so it might not be crossbrowser compliant, just a heads up!
If you want pure JS this is one of the ways to go
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
for(json in data1){
for(objs in data1[json]){
document.write(objs + " : " + data1[json][objs]);
}
}
For simple and quick printing of JSON, one can do something like below and pretty much same goes for objects as well;
var json = {
"title" : "something",
"status" : true,
"socialMedia": [{
"facebook": 'http://facebook.com/something'
}, {
"twitter": 'http://twitter.com/something'
}, {
"flickr": 'http://flickr.com/something'
}, {
"youtube": 'http://youtube.com/something'
}]
};
and now to print on screen, a simple for in loop is enough, but please not e, it won't print array instead will print [object Object]. for simplicity of answer, i won't go in deep to print arrays key and value in screen.
Hope that this will be usefull for someone. Cheers!
for(var i in json) {
document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
console.log(i + ' ' + json[i])
}

Categories

Resources