Displaying nested JSON using JQUERY - javascript

I currently have a live search box that displays json. However I am having issues in working out how to display the nested JSON.
I am looking to display the images and the "closed" days. Any help would be appreciated. I have include my java-script and a sample of my json.
$('#search').keyup(function() {
var searchTerm = $(this).val();
var myExp = new RegExp(searchTerm, "i");
$.get("shops.php",function(data,status){
var response='';
var json = $.parseJSON(data);
shops = json.shops;
$.each(shops, function(index, item) {
if(item.shop_name.search(myExp) != -1){
response += "<h2>"+item.shop_name+"</h2>";
response += "<h2>"+item.distance_citycentre.driving_miles+"</h2>";
});
}
$("#content").html(response);
});
});
Here is a sample of my JSON.
{"shops": [
{ "shop_name":"tesco",
"distance_citycentre": {
"driving_miles":"1.5",
"driving_minutes":"3"
},
"closed": [
"monday",
"wedensday",
"friday"
],
"images" [
{
"description":"lake",
"id":"1"
},
{
"description":"ocean",
"id":"2"
}
]
},
{"shop_name":"asda", etc.......

Here goes your solution
$(document).ready(function() {
var data = '{ "shops":[{"closed":["monday","wedensday","friday"],"images" :[{"description":"lake","id":"1"},{"description":"ocean","id":"2"}]}]}';
var response='';
var json = $.parseJSON(data);
shops = json.shops;
alert(shops[0].closed[0] + " - "+shops[0].closed[1] + " - " +shops[0].closed[2]);
alert(shops[0].images[0].description + " - "+shops[0].images[0].id);
});
And change the JSON Output if possible, There is a little error near "image"<<-- It requires colon ":" You can find the same working model on [JSfiddle][1]
[1]: https://jsfiddle.net/u6exgn7s/ here

If you're talking about how to access json objects in an array which is in an array, you can access them by using array[0].object.array[0].object.array[0].array[0]
In your example you can select closed day 'monday' by using:
item.shops[0].closed[0];
or friday by using:
item.shops[0].closed[2];
You determine the position in the array by [-number from 0 to infinity-]

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 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

Javascript how to parse JSON array

I'm using Sencha Touch (ExtJS) to get a JSON message from the server. The message I receive is this one :
{
"success": true,
"counters": [
{
"counter_name": "dsd",
"counter_type": "sds",
"counter_unit": "sds"
},
{
"counter_name": "gdg",
"counter_type": "dfd",
"counter_unit": "ds"
},
{
"counter_name": "sdsData",
"counter_type": "sds",
"counter_unit": " dd "
},
{
"counter_name": "Stoc final",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "Consum GPL",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "sdg",
"counter_type": "dfg",
"counter_unit": "gfgd"
},
{
"counter_name": "dfgd",
"counter_type": "fgf",
"counter_unit": "liggtggggri "
},
{
"counter_name": "fgd",
"counter_type": "dfg",
"counter_unit": "kwfgf "
},
{
"counter_name": "dfg",
"counter_type": "dfg",
"counter_unit": "dg"
},
{
"counter_name": "gd",
"counter_type": "dfg",
"counter_unit": "dfg"
}
]
}
My problem is that I can't parse this JSON object so that i can use each of the counter objects.
I'm trying to acomplish that like this :
var jsonData = Ext.util.JSON.decode(myMessage);
for (var counter in jsonData.counters) {
console.log(counter.counter_name);
}
What am i doing wrong ?
Thank you!
Javascript has a built in JSON parse for strings, which I think is what you have:
var myObject = JSON.parse("my json string");
to use this with your example would be:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
Here is a working example
EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to #Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage
IMPORTANT: the JSON.parse method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).
In a for-in-loop the running variable holds the property name, not the property value.
for (var counter in jsonData.counters) {
console.log(jsonData.counters[counter].counter_name);
}
But as counters is an Array, you have to use a normal for-loop:
for (var i=0; i<jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
This is my answer:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br>
Last Name: <span id="lname"></span><br>
</p>
<script>
var txt =
'{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.firstName);
}
</script>
</body>
</html>
Just as a heads up...
var data = JSON.parse(responseBody);
has been deprecated.
Postman Learning Center now suggests
var jsonData = pm.response.json();
Something more to the point for me..
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
document.write(contact.phone[1]);
// Output:
// Aaberg, Jesper
// 555-0100
Reference:
https://learn.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript
"Sencha way" for interacting with server data is setting up an Ext.data.Store proxied by a Ext.data.proxy.Proxy (in this case Ext.data.proxy.Ajax) furnished with a Ext.data.reader.Json (for JSON-encoded data, there are other readers available as well). For writing data back to the server there's a Ext.data.writer.Writers of several kinds.
Here's an example of a setup like that:
var store = Ext.create('Ext.data.Store', {
fields: [
'counter_name',
'counter_type',
'counter_unit'
],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
idProperty: 'counter_name',
rootProperty: 'counters'
}
}
});
data1.json in this example (also available in this fiddle) contains your data verbatim. idProperty: 'counter_name' is probably optional in this case but usually points at primary key attribute. rootProperty: 'counters' specifies which property contains array of data items.
With a store setup this way you can re-read data from the server by calling store.load(). You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.
This works like charm!
So I edited the code as per my requirement. And here are the changes:
It will save the id number from the response into the environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++)
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}
The answer with the higher vote has a mistake. when I used it I find out it in line 3 :
var counter = jsonData.counters[i];
I changed it to :
var counter = jsonData[i].counters;
and it worked for me.
There is a difference to the other answers in line 3:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData[i].counters;
console.log(counter.counter_name);
}
You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.
There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.
By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.
Not sure if my data matched exactly but I had an array of arrays of JSON objects, that got exported from jQuery FormBuilder when using pages.
Hopefully my answer can help anyone who stumbles onto this question looking for an answer to a problem similar to what I had.
The data looked somewhat like this:
var allData =
[
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
],
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
]
]
What I did to parse this was to simply do the following:
JSON.parse("["+allData.toString()+"]")

Categories

Resources