not getting data from JSON file using angularjs 1.6 - javascript

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.

Related

Adding data to a Json file using javascript

So I have an existing JSON file where the login data is stored. How can I add new users to this JSON file with JavaScript or JQuery?
This is my JSON-File:
{
"users": [
{
"username": "Tim",
"password": "test1"
},
{
"username": "Tom",
"password": "test2"
}
]
}
At the first put your data from login in data
var data = {
"users": [
{
"username": "Tim",
"password": "test1"
},
{
"username": "Tom",
"password": "test2"
}
]
}
And after that you shoud parse your json and put in jsonData and push your new user in it.
var jsonData = JSON.parse(data); //parse the JSON
jsonData.users .push({ //add new user
username :"Mohammad",
password :"test3",
});
At the end stringfy your json data to a string
data= JSON.stringify(jsonData);

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.

Ionic / AngularJS passing ID through a http.get

I'm having trouble passing the session_id through to my http.get function, any ideas what I'm doing wrong?
Heres my controller:
.controller('feedCtrl', function($scope,$rootScope,$ionicHistory,$state,$http) {
$scope.session_id= sessionStorage.getItem('session_id');
if($scope.session_id == null){
$state.go('login');
}
else {
$http.get('https://m.socialnetwk.com/home/app/feed_load.php?id='+ $scope.session_id +).then(function(rest) {
$scope.records = rest.data;
});
}
})
Errors I see in the code:
You should do to inject sessionStorage service.
Delete + at the end of URL.
Check Example : Link
I wouldnt exactly know what is the problem unless u explain how 'https://m.socialnetwk.com/home/app/' endpoint works and what error does it produce but my suspicion is that as you say you need to PASS the session_id and not GET it, you need to use $http.post instead of $http.get
I have tested your http request in Postman and it's working ok.
https://m.socialnetwk.com/home/app/feed_load.php?id=4235
and returns:
[
{
"firstname": "4235",
"lastname": "Round",
"profile_image": "jpg/55529055162cf0.jpg",
"lastname": "Round",
"iframe": "",
"media_format": "img",
"media_file_format": "jpg",
"media_post_id": "5851875bda5b3",
"media_author_id": "3",
"mediatxt": ""
},
{
"firstname": "4235",
"lastname": "Round",
"profile_image": "jpg/55529055162cf0.jpg",
"lastname": "Round",
"iframe": "",
"media_format": "img",
"media_file_format": "jpg",
"media_post_id": "583c459a745a4",
"media_author_id": "3",
"mediatxt": ""
},
{
"firstname": "4235",
"lastname": "Round",
"profile_image": "jpg/55529055162cf0.jpg",
"lastname": "Round",
"iframe": "",
"media_format": "img",
"media_file_format": "jpg",
"media_post_id": "583c4597778c1",
"media_author_id": "3",
"mediatxt": ""
},
{
}
]
so your error is:
$scope.session_id= sessionStorage.getItem('session_id');
if you print $scope.session you are going to get undefined. So your http request returns a empty array.
Let's fix it
Inject sessionStorage. Let's suppose you are using ngStore, so you need to inject $sessionStorage.
Example:
.controller('feedCtrl', function($scope,$rootScope,$ionicHistory,$state,$http, $sessionStorage )
Change your code:
$scope.session_id= sessionStorage.getItem('session_id');
$http.get('https://m.socialnetwk.com/home/app/feed_load.php?id='+ $scope.session_id +).then(function(rest) {
$scope.records = rest.data;
});
to:
$scope.session_id= $sessionStorage.getItem('session_id');
and delete + at the end of URL.
$http.get('https://m.socialnetwk.com/home/app/feed_load.php?id='+ $scope.session_id).then(function(rest) {
$scope.records = rest.data;
});
As Jackk tell you.
Sorry for my english.

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

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.

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

Categories

Resources