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. .
Related
I am fairly new to web dev and This is my first question on StackOverflow. Apologies if I didn't frame it properly.
Here is my json.
{
"books":
[
{
"_id": "1",
"book_cat": "OLD",
"book_eng_name": "Book1",
"chapter_count": "50"
},
{
"_id": "2",
"book_cat": "OLD",
"book_eng_name": "Book2",
"chapter_count": "40""
}
]
I want to use this json with jquery to append to . First I need to filter __id and then append a statement to the <ul> "Chapter_count" times.
For instance, if I select I am searching for _id 1 I want 50 item list that says
Chapter 1
Chapter 2
...
...
...
Chapter 50
I want to append to ul in the following html:
<html>
<title>Chapters</title>
<body>
<ul></ul>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/
jquery.min.js"></script>
<script type = "text/javascript" src='files/js/Chapter_script.js'></script>
<script type = "text/javascript" src='files/js/books.json'></script>
</body>
</html>
I wrote something like this but didn't work :(
(document).ready(function(){
var search_id = window.location.search;
var chapter_no = search_id.match(/\d+/g);
$.getJSON("files/js/books.json",function(data){
$.each(data.books, function(){
if (this['_id'] == chapter_no ){
for(var i = 0; i <= this['chapter_count']; i++; ){
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}
};
})
});
});
Where chapter_no is extracted from url with window.location.search
Sample url: http://localhost:90/chapters.html?book_id=1
Thanks in advance.
Copy the below code in $.getJSON("files/js/books.json",function(data) function.
var selectedElement = $.grep(data.books, function( element, index ) {
if(chapter_no == element._id)
return element
});
for(var i =0 ; i<=selectedElement[0].chapter_count;i++)
{
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}
first your json is not valid and have syntax error i think the true one is
json ={ "books": [ { "_id": "1", "book_cat": "OLD", "book_eng_name": "Book1",
"chapter_count": "50" }, { "_id": "2", "book_cat": "OLD",
"book_eng_name": "Book2", "chapter_count": "40" } ]}
its sample js code
json.books.forEach(function (b){
if(b._identer code here == "1")
{
for(var i =0 ; i<=b.caphter_count;i++)
{
//put your code here
}
}
})
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" ]
};
I'm working with a response from the Webtrends API in Google apps script and I have a JSON/JS object that looks like this:
"data": [
{
"period": "Month",
"start_date": "2013-12",
"end_date": "2013-12",
"attributes": {},
"measures": {
"Visits": 500
},
"SubRows": [
{
"facebook.com": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"google.co.uk": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"newsnow.co.uk": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"No Referrer": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"t.co": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
}
}
]
}
]
What I need to access is the names i.e facebook.com etc... and visit numbers for each of the SubRows.
I'm able to get the visit numbers, but I can't work out how to get the names. Please note the names will change constantly as different sites will send different amounts of traffic each day.
Section of my code at the moment where I get the visit numbers:
for(i in dObj){
var data = dObj[i].SubRows;
var sd = dObj[i].start_date;
var ed = dObj[i].end_date;
if(sd == ed){
var timep = ""+ sd;
}
else{
var timep = ""+ sd + "-" + ed;
}
var subRows = data[0];
Logger.log(subRows);
for(i in subRows){
var row = subRows[i];
var rmeasures = row.measures;
var rvis = rmeasures.Visits;
values = [timep,"",rvis]; //Blank string for where the name of the site would go
}
}
I've tried the following links, but none of them seem to have the answer:
Getting JavaScript object key list
How to access object using dynamic key?
How to access key itself using javascript
How do I access properties of a javascript object if I don't know the names?
I'm just using vanilla google apps script as I don't have any experience with Jquery etc...
Any help would be much appreciated!
I usually use a little helper function that looks like this:
var keyVal = function(o) {
var key = Object.keys(o)[0];
return {"key": key, "val":o[key]};
} ;
This will map an object with a variable key to a key/value object {key:...., val:{}}, which is usually convenient enough to work with.
describe.only ("stack overflow answer", function(){
it ("is should create a key/value pair" , function(){
var res = keyVal( {
"facebook.com": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
}});
res.key.should.equal('facebook.com');
res.val.attributes.should.deep.equal({});
});
Within the loop, the variable i contains the current key. Replacing the empty string with i should give you what you need.
You might also want to look at some of the more functional tools built into Javascript. Some more concise code might also be more explicit:
data.map(function(datum) {
var timep = datum.start_date == datum.end_date ? datum.end_date :
(data.start_date + "-" + datum.end_date);
return datum.SubRows.map(function(subRow) {
return Object.keys(subRow).map(function(key) {
return [timep, key, subRow[key].measures.Visits];
});
});
});
would return an object something like this:
[
[
[
["2013-12", "facebook.com", 100],
["2013-12", "google.co.uk", 100],
["2013-12", "newsnow.co.uk", 100],
["2013-12", "No Referrer", 100],
["2013-12", "t.co", 100 ]
]
]
]
This just uses map and Object.keys to simplify some of what you're doing with explicit loops.
I am storing a json first in localstorage and then again storing it in final json but I am getting extra backslash in my final json. My code is:
<!DOCTYPE html>
<html>
<body>
<script>
var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
]
localStorage.setItem("myData", JSON.stringify(mi))
var FinalJson = {
"Collected values" : localStorage.getItem("myData"),
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
</script>
</body>
</html>
Output I am getting is:
{"Collected values":"[{\"name\":\"Alex\",\"address\":\"abc\"} {\"name\":\"George\",\"address\":\"efg\"}]","Place":"washington"}
Where am i going wrong that I am getting this extra backslash. How can I remove the extra backslashes? P.S. I don't want to directly store the variable mi in my FinalJson, as it contains some more complicated values which I have removed here for simplicity.
It's stringified twice
var FinalJson = {
"Collected values" : JSON.parse(localStorage.getItem("myData")),
"Place" : "washington"
};
http://jsfiddle.net/Kh5Br/
var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
];
localStorage.setItem("myData", JSON.stringify(mi))
var tes = JSON.parse(localStorage.getItem("myData")); //It was "work". I thougt you missed that
var FinalJson = {
"Collected values" : tes,
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
document.write(tes);
i have some json objects and some of them have some other objects inside them.
if i leave only the json obj that don't have other obj inside them and then apply the template, everything goes well, i get, in this case 3 li elements.
but if i grab the original json obj the results are a bit wired. I believe i need to do a each statement to iterate through each sub json obj from inside each main one
maybe i am a bit confuse so here is some code.
i have some json data like this:
{
"msg_id":"134",
"message":"Nick",
"comment":[
{
"com_id":"9",
"comment":"test",
},
{
"com_id":"10",
"comment":"testtt",
},
{
"com_id":"11",
"comment":"testtttt",
}]
},
{
"msg_id":"134",
"message":"Nick",
},
{
"msg_id":"134",
"message":"Nick",
}
and i am trying to arive at something like this:
Nick
test
testtt
testtttt
Nick
Nick
i've created a template like this:
function messagesTamplate(data)
{
$.each(data, function(index, obj)
{
msg += template.replace( /{{message}}/ig , obj.message );
if(obj.comment) {
$.each(obj.comment, function(key, val)
{
msg += template.replace( /{{comment}}/ig , val.comment );
});
}
});
return msg;
}
then i just append this to the main ul.
thanks
data needs to be an array (see the enclosing [])
var data = [{
"msg_id": "134",
"message": "Nick",
"comment": [{
"com_id": "9",
"comment": "test",
}, {
"com_id": "10",
"comment": "testtt",
}, {
"com_id": "11",
"comment": "testtttt",
}]
}, {
"msg_id": "134",
"message": "Nick",
}, {
"msg_id": "134",
"message": "Nick",
}]
is just this in mustache templates:
{{#data}} //loop through all data
{{message}} //pick out the "message" per iteration
{{#comment}} //loop through all comments in an iterated item
{{comment}} //pick out the comment
{{/comment}}
{{/data}}