Accessing json in javascript and displaying it in html - javascript

I can't figure out why this isn't displaying in my HTML.
I've followed the following examples...
https://www.mkyong.com/javascript/how-to-access-json-object-in-javascript/
http://www.w3schools.com/js/js_json_intro.asp
How to access JSON in JavaScript
Accessing Json in Javascript
I can't seem to figure out where I'm going wrong.
This is what I've got going, currently:
window.onload = function() {
var json = { "year" : "2016",
"months" : [ {"July"}, {"August"}, {"September"} ],
"days" : [ {02}, {03}, {14}, {18}, {10}, {19} ],
"event" : [ {"Fitness assessment"}, {"Pathology-Uric Acid"}, {"Consultation-General and angiogram"}, {"Medication-Asperlone"}, {"Medication-Celestamine"}, {"Fitness assessment"} ]
};
var obj = JSON.parse(json);
document.getElementById("month").innerHTML = obj.months[0];
document.getElementById("day").innerHTML = obj.days[0];
document.getElementById("event").innerHTML = obj.event[0];
document.getElementById("day2").innerHTML = obj.days[1];
document.getElementById("event2").innerHTML = obj.event[1];
document.getElementById("month2").innerHTML = obj.months[1];
document.getElementById("day3").innerHTML = obj.days[2];
document.getElementById("event3").innerHTML = obj.event[2];
document.getElementById("day4").innerHTML = obj.days[3];
document.getElementById("event4").innerHTML = obj.event[3];
document.getElementById("day5").innerHTML = obj.days[4];
document.getElementById("event5").innerHTML = obj.event[4];
document.getElementById("month3").innerHTML = obj.months[2];
document.getElementById("day6").innerHTML = obj.days[5];
document.getElementById("event6").innerHTML = obj.event[5];
};
HTML snippet:
<div class="row liketablerow">
<div class="col-xs-2">
<h4 id="day"></h4>
</div>
<div class="col-xs-2">
<img src="images/icon-fitness.png" class="fitness" >
</div>
<div class="col-xs-2">
<p id="event"></p>
</div>
</div>
All helpful comments are helpful, thank you.

Your "JSON" isn't actually JSON. It's a JavaScript object. As such, JSON.parse won't do anything to it (except break). It's already in the format you need.
var obj = { "year" : "2016",
"months" : [ {"July"}, {"August"}, {"September"} ],
"days" : [ {02}, {03}, {14}, {18}, {10}, {19} ],
"event" : [ {"Fitness assessment"}, {"Pathology-Uric Acid"}, {"Consultation-General and angiogram"}, {"Medication-Asperlone"}, {"Medication-Celestamine"}, {"Fitness assessment"} ] };
^^ change to obj
See here for the different between JSON and a JS object literal:
What is the difference between JSON and Object Literal Notation?
http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/

Your json object is not valid, you are using curly brackets for strings in your arrays which is not the correct way to do it using the json notation, here is how it should be :
var json = {
"year" : "2016",
"months": ["July", "August", "September"],
"days": [02, 03, 14, 18, 10, 19],
"event": ["Fitness assessment", "Pathology-Uric Acid", "Consultation-General and angiogram", "Medication-Asperlone", "Medication-Celestamine", "Fitness assessment" ]};

The javascript object notation seems to be wrong. Your events JS object syntax should be below instead :
var json = { "year" : "2016",
"months" : [ "July", "August", "September" ],
"days" : [ 02, 03, 14, 18, 10, 19 ],
"event" : [ "Fitness assessment", "Pathology-Uric Acid", "Consultation-General and angiogram", "Medication-Asperlone", "Medication-Celestamine", "Fitness assessment" ]
};

Related

How to fetch the length of a string and fetch values?

How to fetch the length and individual values in javascript
here is example data
examples:
"numbers": "248001,248142",
"numbers": "588801,248742,588869"
Actuall code
{
"_id" : ObjectId("579ce69f4be1811f797fbab2"),
"city" : "",
"sdescription" : "",
"categories" : [
"5729f312d549cc3212c8393b"
],
"numbers" : "4555855,421201",
"createdAt" : ISODate("2016-07-30T17:40:47.022Z"),
"month" : 7,
"year" : 2016
}
here is my code and error
let num = numbers.split(',')
(node:5628) UnhandledPromiseRejectionWarning: TypeError: numbers.split is not a function
I have tried split to separate the values but some times it returns an error as number.split is not a function.
I want to return two things:
length: in the first example length should be 2 and in the second example
length should be 3.
2.values should get split
You need to call start from object name objectname.keyname
var obj = { "city": "", "sdescription": "", "categories": [ "5729f312d549cc3212c8393b" ], "numbers": "4555855,421201", "month": 7, "year": 2016 }
var res = obj.numbers.split(',').length;
console.log(res)
You can loop through your object and then for each element access numbers property and then split and find length
let json = [{"numbers": "248001,248142"},{"numbers": "588801,248742,588869"},{"numbers":[]}]
json.forEach(({numbers})=>{
console.log(typeof numbers === 'string' ? numbers.split(',').length : 'Not a string')
})

Converting strings to intergers in JSON using JavaScript

I have the following json
{
"Title": "Test",
"StartDate": {
"Month": "3",
"Year": "1973"
},
"EndDate": {
"Month": "4",
"Year": "1974"
}
}
I want Month and Year values from StartDate and EndDate to be without quotes, like this:
{
"Title": "Test",
"StartDate": {
"Month": 3,
"Year": 1973
},
"EndDate": {
"Month": 4,
"Year": 1974
}
}
EDIT
I'm not creating the json, with JSON.stringify(). My JSON is created by Form Builder module from Angular 2, despite the fact that I'm setting it's type to number, after I change the value, the value gets quotes.
Before saving your JSON, use the parseInt() functions to convert your values into integers. This will remove the quotes.
JSON.stringify({
Month: parseInt( value , 10);
})
See this answer
EDIT
If you made that JSON Object earlier in your JavaScript code, go for #Adrian Lambertz's answer. If you got that JSON as a String from somewhere else and want to convert it, read my answer :
My original answer
Say you got this JSON as a string in your JavaScript code, you could convert the desired values to integers like this :
var events = JSON.parse(JSONStringYouWantToConvert);
// if the JSON String is an array of events that all have a Title, a StartDate and an EndDate
for (var i = 0; i < events.length; i++) {
// else, forget about the loop and the [i] index, the concept remains the same
events[i].StartDate.Month = parseInt(events[i].StartDate.Month);
events[i].StartDate.Year = parseInt(events[i].StartDate.Year);
events[i].EndDate.Month = parseInt(events[i].EndDate.Month);
events[i].EndDate.Year = parseInt(events[i].EndDate.Year);
}
// make a JSON String that wont have the quotes around the Month and Year numbers
var JSONStringConverted = JSON.stringify(events);
Just convert the strings to numbers.
This code is just an example, you can adapt it to whatever your object structure is.
function normalize(target) {
for (const date of ['StartDate', 'EndDate']) {
for (const item of ['Month', 'Year']) {
target[date][item] = Number(target[date][item]);
}
}
}
I can not see the order from which data the result is expeceted, so here two versions.
Object -> JSON (-> Object)
This works with JSON.stringify
and a replacer function for creating numbers for certain keys, like Month and Year.
var dataObj = { "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } },
jsonStr = JSON.stringify(dataObj, function (k, v) {
return ['Month', 'Year'].indexOf(k) !== -1 ? +v : v;
}),
parsed = JSON.parse(jsonStr);
console.log(jsonStr);
console.log(parsed);
JSON -> Object
This works with JSON.parse
and a reviver function for creating numbers for certain keys, like Month and Year.
var jsonStr = '{ "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } }',
parsed = JSON.parse(jsonStr, function (k, v) {
return ['Month', 'Year'].indexOf(k) !== -1 ? +v : v;
});
console.log(parsed);

Angular - create a new array from scope array

I have an angular app which gets data from a JSON response.
How do i create another array, in a different format within my controller?
JSON RESPONSE:
"prices" : [
{"month" : "01", "price" : 599},
{"month" : "02", "price" : 1599},
{"month" : "03", "price" : 2599},
{"month" : "04", "price" : 3599},
]
$scope.prices = data.prices;
Into this for use in a calendar function (new object for every object returned in $scope.prices above):
$scope.events = [{
title: * * $scope.prices.price * * ,
start: new Date(y, $scope.prices.month, 1),
dow: [1, 2, 3, 4, 5, 6],
allDay: true
}];
Many thanks
UPDATE
OK, got the new structure using Array.protoype.map(), but it is placing double quotes around everything.
It is returning:
[{"title":599,"start":"1901-02-01T05:00:00.000Z","dow":[1,2,3,4,5,6],"allDay":true}
when it needs to be:
[{title:"599",start:1901-02-01T05:00:00.000Z,dow:[1,2,3,4,5,6],allDay:true}
Here is my code:
var reformattedArray = array.map(function(obj){
var rObj = {title: obj.price,start: new Date(obj.month, 1),dow:[1,2,3,4,5,6],allDay: true};
return rObj;
});

Show only date in AngularJS

I have a JSON array like this one:
[
{
"user": "345",
"createdOn": "2015-09-01 13:17:22"
},
{
"user": "432",
"createdOn": "2015-09-01 13:27:56"
}
]
In a <div> tag I am doing this:
<div> class="row" ng-repeat="item in array"
{{item.createdOn}}
</div>
The output is : 2015-09-01 13:50:59, but I don't want the time part to be shown, i.e. required output is just 2015-09-01.
I tried using filter but unsuccessfully. Give me some knowledge on this, please.
If your object is fetching data from db and timestamp is returned properly, and your date is formatted as 'yyyy-MM-dd', this should work.
{{item.createdOn| date:'yyyy-MM-dd'}}
Otherwise, format your string as a Date. (This is detailed in other answers.)
$scope.dateOnly= function(timestamp) {
return new Date(timestamp);
}
will help
You need to use Angular filter But Date filters only work with Date objects so first thing you need to convert your strings into Date object.
<div ng-repeat="item in array">
{{getDateFormat(item.createdOn)|date:'yyyy-MM-dd'}}
</div>
Controller:
$scope.array = [{
"user": "345",
"createdOn": "2015-09-01 13:17:22"
}, {
"user": "432",
"createdOn": "2015-09-01 13:27:56"
}];
$scope.getDateFormat = function(timestamp) {
return new Date(timestamp);
}
Plunker
The short answer:
Date filter in Angular works better with Date objects.
Please run this code snippet:
angular.module('app',[]).controller('a',function($scope){
$scope.a='2012-08-30 13:30:00'
$scope.b=new Date('2012-08-30 13:30:00')
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app=app ng-controller=a>
{{a|date:'mm-dd-yy'}}
<hr>
{{b|date:'mm-dd-yy'}}
</div>
This is the fix for you code:
var obj= [{
"user": "345",
"createdOn": new Date("2015-09-01 13:17:22")
},
{
"user": "432",
"createdOn": new Date("2015-09-01 13:27:56")
}
]
You can see the example that when I use date object it works.
If you got the object from external sources you can convert it to Date objects. using this code:
for(var i=0;i<obj.length;i++) obj[i].createdOn=new Date(obj[i].createdOn)
You can create your own custom filter in this case,
Try this,
HTML :
<div ng-controller="MainCtrl">
<div ng-repeat="data in datas">
{{data.createdOn | dateOnly}}
</div>
</div>
angularjs :
angular.module("myapp", []).controller('MainCtrl', ["$scope", function($scope){
var data = [
{
"user": "345",
"createdOn": "2015-09-01 13:17:22"
},
{
"user": "432",
"createdOn": "2015-09-01 13:27:56"
}];
$scope.datas = data;
}])
.filter("dateOnly", function(){
return function(input){
return input.split(' ')[0]; // you can filter your datetime object here as required.
};
});
jsFiddle

HandlebarsJS : Get elements i of each array, then element j, etc.?

Given a JSON such :
{
"network":
[
{ "name": [ "John", "Jill", "June" ] },
{ "town": [ "London", "Paris", "Tokyo" ] },
{ "age" : [ "35", "24", "14" ] }
]
}
Sadly, my input data is in this format and I have to stick with this.
Looking for a final HTML result such :
<ul>
<li>John, London, is 35 years old.</li>
<li>Jill, Paris, is 24 years old.</li>
<li>June, Tokyo, is 14 years old.</li>
</ul>
( So it actually browse the JSON by index, kind of 0, then 1, then 2 :
<ul>
<li>{{name}}[0], {{town}}[0], is {{age}}[0] years old.</li>
<li>{{name}}[1], {{town}}[1], is {{age}}[1] years old.</li>
<li>{{name}}[2], {{town}}[2], is {{age}}[2] years old.</li>
</ul>
)
Is there a native way, using handlebarsJS, to do a template something such :
{{#each network}}<li>{{name}}[i], {{town}}[i], is {{age}}[i] years old.</li>{{/each}}
?
#Hugolpz, you'll want to restructure your data before you begin using your template. templates aren't supposed to contain any sort of 'intelligence'. templates are there for creating output.
<script>
var original = { "network":[
{ "name": [ "John", "Jill", "June" ] },
{ "town": [ "London", "Paris", "Tokyo" ] },
{ "age" : [ "35", "24", "14" ] }
]}
if(
original.network[0]['name'].length != original.network[1]['town'].length &&
original.network[0]['name'].length != original.network[2]['age'].length
) {
console.log( 'data is not uniform' );
return false;
} else {
var dataLength = original.network[0]['name'].length;
}
var dataString = '{"users":[REPLACETHIS]}';
var usersString = '';
for( i=0; i < dataLength; i++ ){
usersString+='{"name":"'+original.network[0]['name'][i]+'","town":"'+original.network[1]['town'][i]+'","age":"'+original.network[2]['age'][i]+'"}';
if( i < dataLength-1 ){
usersString+=',';
}
}
dataString = dataString.replace('REPLACETHIS',usersString);
data = $.parseJSON(dataString);
</script>
you can pass this restructured data to Handlebars for templating output
declare your template ...
<script type="text/x-handlebars-template" id="user-tmpl">
{{#users}}
<p>
name : {{name}} <br />
town : {{town}} <br />
age : {{age}} <br />
</p>
{{/users}}
</script>
and do your handlebar templating ...
<script>
var source = $('#user-tmpl').html();
var bars = Handlebars.compile(source);
$("#target").html(bars(data));
</script>
once you have your data structured in a way that's consistent with what you want to output everything becomes pretty simple
You don't need the {{key}}[index], just {{key}}, #each [Object] already loops over the object and does that behind the scenes. .

Categories

Resources