javascript each - autodetect name of val in (key,val) - javascript

I have a JSON file that has more name value pairs than I care to type in. Either lazy or elegant. Instead of using what I have below where I have to type in all the name values pairs there must be a property of val like val.name so not to have to type all the other pairs out. What's the proper terminology to search find the answer? or the code would be nice too :)
This is what I started using when I thought, "crap, I have to type all that *#&#$ out!"
$.each(data, function(key, val) {
items.push(key + val.TimeStamp + val.bandwidth + );
JSON
{
"Router": "HS-DSCS1",
"router_data": [
{
"TimeStamp": "2012/01/01 06:00:00",
"NeighborIP": "192.168.1.1",
"State": "Full",
"Bytes001": "21362.95663",
"Bytes002": "2.67 KB",
"Bytes003": "9887.99707",
"Bytes004": "1.24 KB",
"Bytes005": "Serial0/1/0"
}
]
}

Seems like you're just doing string concatenation. If so ...
$.each(data, function(key, val) {
items.push(key + $.map(val, String).join('') );
});
DEMO: http://jsfiddle.net/ZVDcy/
Or if you're building a new Array, you could do this...
var items = $.map(data, function(val, key) {
return key + $.map(val, String).join('');
});
DEMO: http://jsfiddle.net/ZVDcy/1/

If I'm understanding your question right, just use a for..in.
for (field in val){
// something with val[field]
}

Related

Convert JSON to HTML: Uncaught TypeError: json.forEach is not a function

I want to convert JSON to HTML to display it on website. I've googled, and this error occurs when when json is a string, and first I need to parse. But when I use JSON.parse, the console says it is already an object (Unexpected token o in JSON at position 1).
$(document).ready(function() {
$("#getMessage").on("click", function() {  
$.getJSON("http://quotes.rest/qod.json", function(json) {
var html = "";
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'blabla'>";
keys.forEach(function(key) {
html += "<b>" + key + "</b>: " + val[key] + "<br>";
});
html += "</div><br>";
});
$(".message").html(html);
});
});
});
json is an object, not an array. You can use forEach only on arrays.
As you have done already, you can iterate over the object's keys like this:
Object.keys(json).forEach(function(key) {
var value = json[key];
...
});
In addition to what everyone else said, it appears that the JSON response does not look like you think it does.
var json = {
"success": {
"total": 1
},
"contents": {
"quotes": [{
"quote": "It's not whether you get knocked down, it...s whether you get up.",
"length": "65",
"author": "Vince Lombardi",
"tags": [
"failure",
"inspire",
"learning-from-failure"
],
"category": "inspire",
"date": "2016-08-09",
"title": "Inspiring Quote of the day",
"background": "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg",
"id": "06Qdox8w6U3U1CGlLqRwFAeF"
}]
}
};
var messageEl = document.querySelector('.message');
messageEl.innerText = json.contents.quotes[0].quote;
<div class="message"></div>
$.getJson already transforms a JSON object into a javascript object, so you would not need to parse it again.
However, your problem starts with forEach, which is an Array method, not an Object method, therefor it will not work in your use case.
var jsonKeys = Object.keys(json); jsonKeys.forEach(...) will work, as Object.keys returns an array of Object keys.

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>

how to get to this JSON structure? in pure JS or JQuery

Below part of json response, how can i get to objects in rows object, i need to do loop for all id and others attributes. , it is'nt a array so active_chats.rows[1].id not work. Thanks in advance for answers
{
"active_chats":{
"rows":{
"2":{
"id":"2",
"nick":"bart",
"status":"1",
"time":"1453463784",
"user_id":"2",
"hash":"183c12afef48ea9942e5c0a7a263ef441039d832",
"ip":"::1",
"dep_id":"2",
"support_informed":"1",
"has_unread_messages":"1",
"last_user_msg_time":"1453476440",
"last_msg_id":"11",
"wait_time":"5171",
"user_tz_identifier":"Europe/Paris",
"nc_cb_executed":"1",
"user_closed_ts":"1453470674",
"department_name":"ECODEMO"
},
"3":{
"id":"3",
"nick":"robert",
"status":"1",
"time":"1453470058",
"user_id":"2",
"hash":"0fae69094667e452b5401552541602d5c2bd73ef",
"ip":"127.0.0.1",
"dep_id":"2",
"user_status":"1",
"support_informed":"1",
"user_typing":"1453479978",
"user_typing_txt":"Gość opuścił chat!",
"last_msg_id":"10",
"wait_time":"3285",
"user_tz_identifier":"Europe/Paris",
"nc_cb_executed":"1",
"user_closed_ts":"1453479983",
"unanswered_chat":"1",
"department_name":"ECODEMO"
}
},
"size":2
Just do
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.info(key + " => " + p[key]);
}
}
where p is your json response object
did some tests here, your json is invalid.. but if fixed:
for(var row in response.active_chats.rows)
{
for (var key in response.active_chats.rows[row]) {
console.log(key + " => " + response.active_chats.rows[row][key]);
}
}
fiddle example (printing to console)
should do the trick
In order to access the id you would have to do:
var number = 2
var idVal = obj.active_chats.rows[number].id; // idVal = 2
Here obj being whatever variable you saved the JSON in. Looping through the length of active_chats and rows would then help you step through each value.
Also, you can toss your JSON to the text box on this site to get a better picture of what is going on: http://jsbeautifier.org

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])
}

using $.getJSON with JSCharts

I am a beginner in JSCharts. I'm using $.getJSON to load json files and
with them i want to create charts with JSCharts. I am getting the message:
JSChart: Input data in wrong format for selected chart type
var x= new Array();
$.getJSON('test.json', function(data) {
$.each(data, function(key, val) {
x.push(val[0].abs);
x.push(val[1].ord)
});
});
var myChart = new JSChart('chartcontainer', 'line');
myChart.setDataArray(x);
myChart.draw();
Any ideas how to change to format, so it can be accepted by jscharts?
Even if i pass them as integers they are not accepted.
Json looks like this:
" cordonnee " : [ { " abs " : "45" } ,
{ " ord " : "12" }
],
"autre" : [ { "abs": "68" } ,
{ " ord " : "13" }
]
Thank you
Try to parse the values as Integers.
$.each(data, function(key, val) {
x.push(parseInt(val[0].abs));
x.push(parseInt(val[1].ord));
});
You are providing the data as a 1 dimensional array, it has to be 2 dimensional for a line chart.
$.each(data, function(key, val) {
var y = new Array();
y.push(val[0].abs);
y.push(val[1].ord);
x.push(y);
});
see JSCharts how to use line graphs for more details

Categories

Resources