How to render mustache using : external json that have function as variable - javascript

I want to render mustache.js example. but I want to get data from external file.
I copy this data to "mydata.json" :
{
"beatles": [
{ "firstName": "John", "lastName": "Lennon" },
{ "firstName": "Paul", "lastName": "McCartney" },
{ "firstName": "George", "lastName": "Harrison" },
{ "firstName": "Ringo", "lastName": "Starr" }
],
"name": function () {
return this.firstName + " " + this.lastName;
}
}
I copy template to "template.html" :
{{#beatles}}
* {{name}}
{{/beatles}}
and render this files by this code :
$.get('template.html', function(template)
{
$.get('mydata.json',function(datas)
{
var rendered = Mustache.render(template, datas);
$('#content').html(rendered);
}
}
these codes not working until I remove function(s) from data file.
I tried : different 'dataType' in JQuery ajax request.
I tried : get data as text and then jQuery.parseJSON that data.
I tried : regular and LAMBDA syntax in functions scripts.
but I cant solve this problem.

I find the answer .
AJAX request datatype must be 'script' to receive data as json and function together.

Related

not getting data from JSON file using angularjs 1.6

I am trying to get data from my JSON file using AngularJs 1.6
myApp.controller("homeCtrl", function($scope, $http) {
$scope.Data = [];
var getJsonData = function() {
$http.get('contactlist.json').then(function(response) {
$scope.Data = response.data;
console.log(response.data);
});
}
getJsonData();
});
But it's not going to response I am putting debug on then line but my page opened without stopping on debug response. So it's not going on then(function(reponse){
My JSON File:
var contactList = [
{
"firstName": "Joe",
"lastName": "Perry",
"contactNumber": "444-888-1223",
"contactEmail": "joe#cordis.us"
},
{
"firstName": "Kate",
"lastName": "Will",
"contactNumber": "244-838-1213",
"contactEmail": "kate#cordis.us"
}
];
Got it resolved. Issue was because of semicolon at the end of json file data.
Got this error when tried pasting in Plunker editor
My Bad.
Change your json file to(your json is not valid):
[{"firstName":"Joe","lastName":"Perry","contactNumber":"444-888-1223","contactEmail":"joe#cordis.us"},{"firstName":"Kate","lastName":"Will","contactNumber":"244-838-1213","contactEmail":"kate#cordis.us"}]
Remove var contactList = from you JSON file and place the JSON contents only
like:
[
{
"firstName": "Joe",
"lastName": "Perry",
"contactNumber": "444-888-1223",
"contactEmail": "joe#cordis.us"
},
{
"firstName": "Kate",
"lastName": "Will",
"contactNumber": "244-838-1213",
"contactEmail": "kate#cordis.us"
}
]
var contactList = <something> meant it's javascript code need to be execute, but you are reading the file and parsing it as a json data and not executing as js file, so make it like a json file so the contents is only json string and not some javascript code.

While retrieve a model by ID from a Backbone.js collection returning undefined

I'm trying to get a model from a collection by it's ID and display in view. After instantiating a model, I'm using the methods like get(), at() but it's returning undefined.
My collection:
[
{
"id": "1",
"firstname": "Abc",
"lastname": "Xyz"
},
{
"id": "2",
"firstname": "Klm",
"lastname": "Opq"
},
{
"id": "2",
"firstname": "rst",
"lastname": "Yvw"
}
]
Instantiation:
var persons = new PersonCollection();
console.log(persons.get(1)); // undefined
NOTE: I'm getting all the models in console (Not an issue). I want only to fetch a model by it's id name.
fetch is async so you need to place your code inside success callback
persons.fetch({
success: function() {
console.log('Now I have something: ', persons.get(1))
}
})
console.log('Nothing here: ', persons.get(1))
BTW to fetch single model by id you could use Model#fetch instead

Edit content of JSON file imported to MongoDB

I'm using Node.js to:
Query an external API.
Save JSON result to file.
Import query result to MongoDB.
Example of code:
//Query the API and save file
var file = '../data/employees.json';
tl.employees.all(function(response) {
fs.writeFile(file, JSON.stringify(response, function(key, value) {
var result = value;
return result;
}, 3, 'utf8'));
//Inserts API response above to MongoDB
var insertDocument = function(db, callback) {
db.collection('employees').insert(response, function(err, result) {
assert.equal(err, null);
console.log("Step 2: Inserted Employees");
callback();
});
};
This is all working fine, and I'm getting the following JSON saving to file and importing to MongoDB:
{
"data": [
{
"full name": "Keith Richards",
"age": 21,
"userName": "keith1#keith.com",
"employeeDetails": {
"id": 102522
}
},
{
"full name": "Jim Morrison",
"age": 27,
"userName": "jim#jim.com",
"employeeDetails": {
"id": 135522
}
}
]
}
The problem is that this gets imported to MongoDB as 1 object because of the "data" part.
Like this:
{
"_id" : ObjectId("58ae5ceac10d7a5005fc8370"),
"data" : [
{ // contents as shown in JSON above ..
This makes aggregation and matching really hard (or not possible).
Is there a way of stripping out the "data" part and only importing the contents of it, so each 'employee' would become it's own object like this:
[
{
"_id" : ObjectId("58ae5ceac10d7a5005fc8370"),
"full name": "Keith Richards",
"age": 21,
"userName": "keith1#keith.com",
"employeeDetails": {
"id": 102522
}
},
{
"_id" : ObjectId("234332c10d7a5005fc8370"),
"full name": "Jim Morrison",
"age": 27,
"userName": "jim#jim.com",
"employeeDetails": {
"id": 135522
}
}
]
So you can parse the Json before sending it to file. After getting the result, use parseJSON(data) to check if it contains "data" field. if yes, get the arrays inside that and store them to file.
Basically, I have explained a bit more to what #Bertrand has said.
Hope this helps.

Json in sessionStorage with array of objects

Hi all I am creating a Json and adding it to Sessionstorage as follows
<script type="text/javascript">
function addMoreProducts() {
if (sessionStorage.getItem("empData") === null) {
var empInformation = {
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
}
var x = JSON.stringify(empInformation);
sessionStorage.setItem("empData", x);
}
else {
if (sessionStorage.getItem("empData") != null) {
var empInformation = {
"employees": [
{ "firstName": "John1", "lastName": "Doe1" },
{ "firstName": "Anna1", "lastName": "Smith1" },
{ "firstName": "Peter1", "lastName": "Jones1" }
]
}
var v = sessionStorage.getItem("empData").toString();
var jParse = JSON.stringify(v);
var jparse1 = JSON.stringify(empInformation);
var arrayOfObjects = [jParse, jparse1];
}
var vparse = JSON.stringify(arrayOfObjects);
var vparse1 = JSON.parse(vparse);
sessionStorage.removeItem('empData');
sessionStorage.setItem("empData", vparse);
}
}
</script>
But when I retrieve the data from sessionStorage after assigning data this is not giving me proper json format can some one help me. This is the format I am getting
"["\"{\\"employees\\":[{\\"firstName\\":\\"John\\",\\"lastName\\":\\"Doe\\"},{\\"firstName\\":\\"Anna\\",\\"lastName\\":\\"Smith\\"},{\\"firstName\\":\\"Peter\\",\\"lastName\\":\\"Jones\\"}]}\"","{\"employees\":[{\"firstName\":\"John1\",\"lastName\":\"Doe1\"},{\"firstName\":\"Anna1\",\"lastName\":\"Smith1\"},{\"firstName\":\"Peter1\",\"lastName\":\"Jones1\"}]}"]"
When I watch it in console. Also I am using restful service where my service holds a datatable as a parameter how can I pass this json object to that method as DataTable
This is actually a very wide discussed issue:
This is what is proposed by microsof in this article
If this function causes a JavaScript parser error (such as "SCRIPT1014: Invalid character"), the input text does not comply with JSON syntax. To correct the error, do one of the following:
Modify the text argument to comply with JSON syntax. For more information, see the BNF syntax notation of JSON objects.
For example, if the response is in JSONP format instead of pure JSON, try this code on the response object:
var fixedResponse = response.responseText.replace(/\\'/g, "'");
var jsonObj = JSON.parse(fixedResponse);

Parse JSON array of hashes into jQuery tokenInput

I have jQuery token input implemented for tagging purposes where a user can search for a tag or create a new one thanks to railscasts ep#382 & ep#258. Data comes from the tags.json url which is the index action of the tags controller. The data from tags.json looks like so:
[
{
"created_at":"2013-06-21T16:30:19Z",
"explanation":"hitting the hosel of the club",
"id":8,
"name":"shank",
"updated_at":"2013-06-21T16:30:19Z",
"updated_by":"andy"
},
{
"created_at":"2013-06-22T17:40:37Z",
"explanation":"hitting the ground before the ball",
"id":12,
"name":"chunk",
"updated_at":"2013-06-22T17:40:37Z",
"updated_by":"andy"
}
]
My tags have a name as well as an explanation so I would like to include them in the results list like the Token and Results Formatting demo here http://loopj.com/jquery-tokeninput/demo.html#formatting.
The code below (number of entries omitted for brevity) is from the jQuery tokenInput Token and Results Formatting demo.
Instead of having "name": "Shank" manually entered here as well as the other omitted entries, how can I extract the name and explanation from tags.json hash and use them in the same was as the results formatter line, e.g. item.name & item.explanation?
tags.js
jQuery(function() {
var question = $('#question_tag_tokens')
return question.tokenInput([{
"name": "Shank",
"explanation": "hitting the hosel of the club"
}
], {
propertyToSearch: ["name"],
resultsFormatter: function(item){ return "<li>" + "<div class='tag' style='display:inline;color:#fff;'>" + item.name + "</div>" + " " + item.explanation + "</li>" },
prePopulate: question.data('preload')
});
});
The source for the example you referred to goes like this:
$(document).ready(function() {
$("#demo-input-local-custom-formatters").tokenInput(
[{
"first_name": "Arthur",
"last_name": "Godfrey",
"email": "arthur_godfrey#nccu.edu",
"url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
},
{
"first_name": "Adam",
"last_name": "Johnson",
"email": "wravo#yahoo.com",
"url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
},
...
],
{
propertyToSearch: "first_name",
resultsFormatter: function(item){ ... },
tokenFormatter: function(item) { ... }
});
});
tokenInput seems to take an array of objects. Once you load the json with ajax, you just pass it in and tell it what field to search on and some callbacks to format the results.

Categories

Resources