I'm new to JSON, WebDevelopment, Javascript ...
I have the following JSON file
{
"component": "A",
"status": 0,
"children": [
{
"component": "AA",
"status": 0,
"children": [
{
"component": "AAA",
"status": 0,
"children": []
},
{
"component": "AAB",
"status": 0,
"children": []
}
]
},
{
"component": "AB",
"status": 0,
"children": [
{
"component": "ABA",
"status": 0,
"children": []
},
{
"component": "ABB",
"status": 0,
"children": []
}
]
}
]
}
I need to read it using Javascript/Jquery and then display it. Later on I should develop code for Onclicking a "component A" on a webpage a list of components under it
should be displayed and so on.Depending on the status variable a color is to be assigned to the component displayed ( in the form of an image like a box or something)
I wrote the following code:
<html>
<head>
<title>Demo</title>
</head>
<body>
<script src="jquery-1.9.1.min.js"></script>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
var myItems;
$.getJSON('jsonfile.json', function(data) {
JSONArray children = jsonfile.getJSONArray("children");
});
});
</script>
</body>
</html>
Firstly what are the javascript equivalent of java functions for JSON like getJSONArray(), getJSONObject() etc
Secondly any suggestions as to how i go about printing the details using what API's etc.
please show the syntax of $.each in this context
var result = $('#result');
$.each(obj.children, function(i, v){
result.append('<div>' + i + ' - ' + v.component + '</div>');
});
Demo: http://jsfiddle.net/LbJBm/
Documentation: jQuery.each()
var response = JSON.stringify(jsonvar);
response = JSON.parse(response);
response.componet will gives you A and thus you can access hte elements.
Related
I'm a novice using JavaScript syntax and am having trouble adapting any solutions I find to match this.
This is a part of my code:
var arr1 = response;
console.log(arr1);
**This is the response/console logged arr1:
{
"channels": {
"1620184778889x527731420801269760": [
{
"channel": "1620184778889x527731420801269760",
"timetoken": "16204064644032062",
"message": {
"content": "44444444444",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618599897203x154294096401530880": [
{
"channel": "1618599897203x154294096401530880",
"timetoken": "16203351496721278",
"message": {
"content": "fffffffdd",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618613571551x955443898854408200": [
{
"channel": "1618613571551x955443898854408200",
"timetoken": "16204261556065826",
"message": {
"content": "78777",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
]
}
}
Trying to:
I need to get the following data:
1.channel
2.timetoken
3.message > content
4.message > sender
And then I need to dynamically generate an innerHTML property for each channel in the array (the amount of channels will frequently vary).
Something like this for each channel returned (incorrect syntax, just an example):
document.getElementById(channel).innerHTML = sender + ' ' + content + ' ' + timetoken;
I am having difficulty adapting other similar solutions to retrieve the nested array items and use loops. I think I need a loop to go through the channels to retrieve the data and also a loop to generate the innerHTML items, but I have been trying for days and can't get it, I am hoping someone well versed can assist.
Thank you.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
<script>
let dataObject = {
"channels": {
"1620184778889x527731420801269760": [
{
"channel": "1620184778889x527731420801269760",
"timetoken": "16204064644032062",
"message": {
"content": "44444444444",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618599897203x154294096401530880": [
{
"channel": "1618599897203x154294096401530880",
"timetoken": "16203351496721278",
"message": {
"content": "fffffffdd",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618613571551x955443898854408200": [
{
"channel": "1618613571551x955443898854408200",
"timetoken": "16204261556065826",
"message": {
"content": "78777",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
]
}
}
for (let channelName in dataObject.channels) {
for (let item of dataObject.channels[channelName]) {
const channel = item.channel;
const timetoken = item.timetoken;
const content = item.message.content;
const sender = item.message.sender;
const messageType = item.messageType;
const uuid = item.uuid;
// do whatever you want with these data
console.log(channel, timetoken, content, sender, messageType, uuid);
}
}
</script>
I´ve got an array in this format:
var items = [{
"link": {
"0": "http://www.example.com/"
},
"title": {
"0": "example"
}
}, {
"link": {
"0": "http://www.example2.com"
},
"title": {
"0": "example2"
}
}]
I can´t figure out how to loop through it and display its values in HTML.
Im using jquery and have tried using an each-loop:
$.each( items, function(i, item) {
console.log(item); // Uncaught TypeError: Cannot use 'in' operator to search for '6271' in
})
Help appreciated. Thanks!
EDIT:
Your code works in the example i posted above. I will accept asasp.
I noticed however that the real json im trying to loop is not always properly formatted which leads to a crash:
var items = [{
"link": {
"0": "http://www.example.com/"
},
"title": {
"0": "example"
}
}, {
"link": {
"0": "http://www.example2.com"
},
"title": {
"0": "example2: "
some text here ""
}
}]
When looping this array i get:
Uncaught SyntaxError: Unexpected identifier
Is there a way to maybe skip all "broken" objects?
Here you go with a solution
var items = [{
"link": {
"0": "http://www.example.com/"
},
"title": {
"0": "example"
}
}, {
"link": {
"0": "http://www.example2.com"
},
"title": {
"0": "example2"
}
}];
$.each( items, function(i, item) {
$("body").append(`<span class="title">${item.title["0"]}:</span> <span>${item.link["0"]}</span><br/>`);
});
.title {
font-weight: bold;
font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Each item is an object, to get the link value I've provided in the solution.
Fast and dirty:
for (item of items) {
console.log(item.link[0])
console.log(item.title[0])
}
I know there are plenty of questions about iterating through JSON objects but I haven't found one that quite relates to my exact problem. This is the JSON that I'm trying to iterate through:
psinsights = {
"kind": "pagespeedonline#result",
"id": "/speed/pagespeed",
"responseCode": 200,
"title": "PageSpeed Home",
"score": 90,
"pageStats": {
"numberResources": 22,
"numberHosts": 7,
"totalRequestBytes": "2761",
"numberStaticResources": 16,
"htmlResponseBytes": "91981",
"cssResponseBytes": "37728",
"imageResponseBytes": "13909",
"javascriptResponseBytes": "247214",
"otherResponseBytes": "8804",
"numberJsResources": 6,
"numberCssResources": 2
},
"formattedResults": {
"locale": "en_US",
"ruleResults": {
"AvoidBadRequests": {
"localizedRuleName": "Avoid bad requests",
"ruleImpact": 0.0
},
"MinifyJavaScript": {
"localizedRuleName": "Minify JavaScript",
"ruleImpact": 0.1417,
"urlBlocks": [
{
"header": {
"format": "Minifying the following JavaScript resources could reduce their size by $1 ($2% reduction).",
"args": [
{
"type": "BYTES",
"value": "1.3KiB"
},
{
"type": "INT_LITERAL",
"value": "0"
}
]
},
"urls": [
{
"result": {
"format": "Minifying $1 could save $2 ($3% reduction).",
"args": [
{
"type": "URL",
"value": "http://code.google.com/js/codesite_tail.pack.04102009.js"
},
{
"type": "BYTES",
"value": "717B"
},
{
"type": "INT_LITERAL",
"value": "1"
}
]
}
},
{
"result": {
"format": "Minifying $1 could save $2 ($3% reduction).",
"args": [
{
"type": "URL",
"value": "http://www.gmodules.com/ig/proxy?url\u003dhttp%3A%2F%2Fjqueryjs.googlecode.com%2Ffiles%2Fjquery-1.2.6.min.js"
},
{
"type": "BYTES",
"value": "258B"
},
{
"type": "INT_LITERAL",
"value": "0"
}
]
}
}
]
}
]
},
"SpriteImages": {
"localizedRuleName": "Combine images into CSS sprites",
"ruleImpact": 0.0
}
}
},
"version": {
"major": 1,
"minor": 11
}
};
Now, I'm trying to write a function that iterates through all of the ruleResults objects and returns an array of the localizedRuleName properties. According to the JSON, ruleResults has three member objects (AvoidBadRequests, MinifyJavaScript, and SpriteImages). Each of these has a localizedRuleName property I'm trying to access, but when I print out my array, it's blank. Here's how I've written my function:
function ruleList(results) {
var ruleArray = [];
for(var ruleName in results.formattedResults.ruleResults){
ruleArray[counter] = results.formattedResults.ruleResults[ruleName].localizedRuleName;
}
return ruleArray;
}
console.log(ruleList(psinsights));
Can you guys help me get on the right track? I used basically this same method to iterate through the pageStats of the JSON and it worked perfectly. I'm not sure why I can't get it to work with these deeper nested objects and properties.
your problem is not your iteration, but your undefined variable "counter".
Instead of using a counter can use the "push" function:
function ruleList(results) {
var ruleArray = [];
for(var ruleName in results.formattedResults.ruleResults){
ruleArray.push(results.formattedResults.ruleResults[ruleName].localizedRuleName);
}
return ruleArray;
}
fiddle: https://jsfiddle.net/fo9h56gh/
Hope this helps.
you're probably getting a javascript error since counter is not defined. you can try this:
function ruleList(results) {
var ruleArray = [];
var counter = 0;
for(var ruleName in results.formattedResults.ruleResults){
ruleArray[counter] = results.formattedResults.ruleResults[ruleName].localizedRuleName;
counter++;
}
return ruleArray;
}
I have been playing around with the Angular UI Tree drag and drop and have come by an issue that has stumped me. The json is being received from my services. When it is received by my controller, I must format it properly with an empty array so it will be able to hold childen:
Formatting:
function categorySuccessPost(data) {
var emptyCategoryArray = {
Categories: []
}
for (var i = 0; i < data.length; i++) {
$.extend(data[i], emptyCategoryArray);
}
$scope.categoryData = data;
}
It is now formatted and looks like:
[ { "CategoryId": 27054, "MerchantId": 5594, "ProductCategoryId": 1310,
"Name": "BulkUpload", "Description": "BulkUpload", "DateCreated":
"/Date(1446793200000-0000)/", "IsActive": true, "IsDefault": false, "ItemCount":
5, "ResponseStatus": { "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15,
"Categories": [] }, { "CategoryId": 23267, "MerchantId": 5594,
"ProductCategoryId": 818, "Name": "Coupon", "Description": "Coupon",
"DateCreated": "/Date(-62135596800000-0000)/", "IsActive": true, "IsDefault":
true, "ItemCount": 1, "ResponseStatus": { "ErrorCode": "SUCCESS" },
"TotalRecordCount": 15, "Categories": [] } }
I have tried two different functions when attempting to add a child:
Function 1 (Uses model value):
$scope.newSubItem = function (scope) {
var currentCategoryData = scope.$modelValue;
currentCategoryData.Categories.push({
CategoryId: currentCategoryData.CategoryId * 10 + currentCategoryData.Categories.length,
Name: currentCategoryData.Name + '.' + (currentCategoryData.Categories.length + 1),
Categories: []
});
};
Function 2 (Uses index of object in the array, and yes, I have made sure the correct index is being passed):
$scope.newSubItem = function (index) {
var array = $scope.categoryData;
array[index].Categories.push({
CategoryId: 12312,
Name: 'test',
Categories: []
});
};
The issue is that instead of pushing the new data to the selected index, it adds the json to every Categories :
[ { "CategoryId": 27054, "MerchantId": 5594, "ProductCategoryId": 1310,
"Name": "BulkUpload", "Description": "BulkUpload", "DateCreated":
"/Date(1446793200000-0000)/", "IsActive": true, "IsDefault": false, "ItemCount":
5, "ResponseStatus": { "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15,
"Categories": [ { "CategoryId": 12312, "Name": "test", "Categories": [] } ] }, {
"CategoryId": 23267, "MerchantId": 5594, "ProductCategoryId": 818, "Name": "Coupon", "Description": "Coupon", "DateCreated": "/Date(-62135596800000-
0000)/", "IsActive": true, "IsDefault": true, "ItemCount": 1, "ResponseStatus":
{ "ErrorCode": "SUCCESS" }, "TotalRecordCount": 15, "Categories": [ {
"CategoryId": 12312, "Name": "test", "Categories": [] } ] }
I am not showing the HTML because it does not appear to be an issue. Here's where I have narrowed it down to, but still have no explanation:
If I use the data that goes through the $.extend method then it adds a child to every parent. But if I copy the json that is generated after the formatting, put it into and object and then read from that, then it only adds a child to the selected parent like I want. But it is necessary to add the empty array. Any idea why this is happening and any solution?
EDIT
One more piece of information that may be important: When I add a full Category (different function), rather than adding a subcategory and then try to add a child to the newly generated category then it works correctly (adding only a child to that category):
$scope.addCategory = function () {
var name = $scope.categoryName;
// Temporary
var categoryId = Math.floor((Math.random() * 50000) + 1)
console.log(name, categoryId)
$scope.categoryData.unshift({ CategoryId: categoryId, Name: name, Categories: [] })
$scope.categoryName = "";
$("#addCategoryModal").modal('hide');
Notification.success({ message: 'Category Added Successfully!', delay: 3000 });
}
I'm still not sure exactly why this is happening, but this was my solution to fixing the issue:
Remove the $.extend for loop and $.extend function:
function categorySuccessPost(data) {
$scope.categoryData = data;
}
When adding an item, check if the array has been initialized, if not, create it in the current scope:
$scope.newSubItem = function (scope) {
var currentCategoryData = scope.$modelValue;
if(currentCategoryData.Categories === 'undefined'){
currentCategoryData.Categories = [];
}
currentCategoryData.Categories.push({
CategoryId: currentCategoryData.CategoryId * 10 + currentCategoryData.Categories.length,
Name: currentCategoryData.Name + '.' + (currentCategoryData.Categories.length + 1),
Categories: []
});
};
The issue with this method is that you can no longer drag a node into an empty parent.
I'm trying to loop through "tabs" in the Json object using AngularJS? How can I do it?
var model = {
"$id": "1",
"tabs": [{
"$id": "2",
"id": 2,
"name": "Output",
"layoutId": 1,
"order": 1,
"dashboardId": 1
}, {
"$id": "15",
"id": 3,
"name": "Yield",
"layoutId": 1,
"order": 2,
"dashboardId": 1
}, {
"$id": "24",
"id": 4,
"name": "Trend",
"layoutId": 1,
"order": 3,
"dashboardId": 1
}],
"id": 1,
"name": "Test",
"title": "Test",
"description": "Test Dashboard",
"createDate": "2015-06-08T00:00:00+01:00",
"ownerId": 1,
"enabled": true
};
When I try this, I get "undefined" in the console.
angular.forEach(model.tabs, function (tab) {
console.log(tab.name);
});
not sure what I'm doing wrong?
EDIT:
The data is coming from ASP.Net controller:
$http.get("/Dashboards/GetDashboardData").success(function (data) {
model = data;
angular.forEach(model.tabs, function (tab) {
console.log(tab.name);
});
}).error(function (data) {
console.log("error");
});
I expect that the model is not ready at the time you loop though it. Run the following code with your inspector open - the code you have is correct, but in your case fails because model isn't ready when you run the loop.
If you're loading data asyncronously you'll want to wait until the data is returned, either using a promise or a callback, and the loop through it.
var model = {
"tabs": [{
"name": "Output",
}, {
"name": "Yield",
}, {
"name": "Trend",
}],
};
angular.forEach(model.tabs, function (tab) {
console.log(tab.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Ok I found the answer. It looks like my controller returns Json object as a string, so I have to switch it to object before I can use it as an object.
I have add this line before using model in the loop:
model = JSON.parse(data);
The whole solution with promise (not sure if I need it now):
DataService.getDashboardData().then(function (data) {
model = JSON.parse(data);
angular.forEach(model.tabs, function (tab) {
console.log(tab);
});
});
app.service("DataService", ["$http", "$q", function ($http, $q) {
return {
getDashboardData: function () {
var dfd = $q.defer();
$http.get('/Dashboards/GetDashboardData').success(function (result) {
dfd.resolve(result);
});
return dfd.promise;
}
};
}]);