AngularJS: factory $http.get JSON file - json

I am looking to develop locally with just a hardcoded JSON file. My JSON file is as follows (valid when put into JSON validator):
{
"contentItem": [
{
"contentID" : "1",
"contentVideo" : "file.mov",
"contentThumbnail" : "url.jpg",
"contentRating" : "5",
"contentTitle" : "Guitar Lessons",
"username" : "Username",
"realname" : "Real name",
"contentTags" : [
{ "tag" : "Guitar"},
{ "tag" : "Intermediate"},
{ "tag" : "Chords"}
],
"contentAbout" : "Learn how to play guitar!",
"contentTime" : [
{ "" : "", "" : "", "" : "", "" : ""},
{ "" : "", "" : "", "" : "", "" : ""}
],
"series" :[
{ "seriesVideo" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "1", "seriesTitle" : "How to Play Guitar" },
{ "videoFile" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "2", "seriesTitle" : "How to Play Guitar" }
]
},{
"contentID" : "2",
"contentVideo" : "file.mov",
"contentThumbnail" : "url.jpg",
"contentRating" : "5",
"contentTitle" : "Guitar Lessons",
"username" : "Username",
"realname" : "Real name",
"contentTags" : [
{ "tag" : "Guitar"},
{ "tag" : "Intermediate"},
{ "tag" : "Chords"}
],
"contentAbout" : "Learn how to play guitar!",
"contentTime" : [
{ "" : "", "" : "", "" : "", "" : ""},
{ "" : "", "" : "", "" : "", "" : ""}
],
"series" :[
{ "seriesVideo" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "1", "seriesTitle" : "How to Play Guitar" },
{ "videoFile" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "2", "seriesTitle" : "How to Play Guitar" }
]
}
]
}
I've gotten my controller, factory, and html working when the JSON was hardcoded inside the factory. However, now that I've replaced the JSON with the $http.get code, it doesn't work. I've seen so many different examples of both $http and $resource but not sure where to go. I'm looking for the simplest solution. I'm just trying to pull data for ng-repeat and similar directives.
Factory:
theApp.factory('mainInfoFactory', function($http) {
var mainInfo = $http.get('content.json').success(function(response) {
return response.data;
});
var factory = {}; // define factory object
factory.getMainInfo = function() { // define method on factory object
return mainInfo; // returning data that was pulled in $http call
};
return factory; // returning factory to make it ready to be pulled by the controller
});
Any and all help is appreciated. Thanks!

Okay, here's a list of things to look into:
1) If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See:
https://code.google.com/archive/p/browsersec/wikis/Part2.wiki#Same-origin_policy
Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder).
2) The success function returned from $http.get() already splits up the result object for you:
$http({method: 'GET', url: '/someUrl'}).success(function(data, status, headers, config) {
So it's redundant to call success with function(response) and return response.data.
3) The success function does not return the result of the function you pass it, so this does not do what you think it does:
var mainInfo = $http.get('content.json').success(function(response) {
return response.data;
});
This is closer to what you intended:
var mainInfo = null;
$http.get('content.json').success(function(data) {
mainInfo = data;
});
4) But what you really want to do is return a reference to an object with a property that will be populated when the data loads, so something like this:
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
mainInfo.content will start off null, and when the data loads, it will point at it.
Alternatively you can return the actual promise the $http.get returns and use that:
theApp.factory('mainInfo', function($http) {
return $http.get('content.json');
});
And then you can use the value asynchronously in calculations in a controller:
$scope.foo = "Hello World";
mainInfo.success(function(data) {
$scope.foo = "Hello "+data.contentItem[0].username;
});

I wanted to note that the fourth part of Accepted Answer is wrong
.
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
The above code as #Karl Zilles wrote will fail because obj will always be returned before it receives data (thus the value will always be null) and this is because we are making an Asynchronous call.
The details of similar questions are discussed in this post
In Angular, use $promise to deal with the fetched data when you want to make an asynchronous call.
The simplest version is
theApp.factory('mainInfo', function($http) {
return {
get: function(){
$http.get('content.json'); // this will return a promise to controller
}
});
// and in controller
mainInfo.get().then(function(response) {
$scope.foo = response.data.contentItem;
});
The reason I don't use success and error is I just found out from the doc, these two methods are deprecated.
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.

this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:
menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) {
console.log("success!");
$scope.appetizers = data.appetizers;
console.log(data.appetizers);
});
});

I have approximately these problem. I need debug AngularJs application from Visual Studio 2013.
By default IIS Express restricted access to local files (like json).
But, first: JSON have JavaScript syntax.
Second: javascript files is allowed.
So:
rename JSON to JS (data.json->data.js).
correct load command ($http.get('App/data.js').success(function (data) {...
load script data.js to page (<script src="App/data.js"></script>)
Next use loaded data an usual manner. It is just workaround, of course.

++ This worked for me. It's vanilla javascirpt and good for use cases such as de-cluttering when testing with ngMocks library:
<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!-- Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>
This is your javascript file that contains the JSON data
// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
"Title": "Star Wars",
"Year": "1983",
"Rated": "N/A",
"Released": "01 May 1983",
"Runtime": "N/A",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "N/A",
"Writer": "N/A",
"Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "N/A",
"Metascore": "N/A",
"imdbRating": "7.9",
"imdbVotes": "342",
"imdbID": "tt0251413",
"Type": "game",
"Response": "True"
};
Finally, work with the JSON data anywhere in your code
// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;
Note:- This is great for testing and even karma.conf.js accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development environment.
// extract from karma.conf.js
files: [
'json-data/JSONSearchResultHardcodedData.js',
'json-data/JSONFindByIdResults.js'
...
]
Hope this helps.
++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733
UPDATE
An easier way that worked for me is just include a function at the bottom of the code returning whatever JSON.
// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
return {
"Title": "Bri Squared",
"Year": "2011",
"Rated": "N/A",
"Released": "N/A",
"Runtime": "N/A",
"Genre": "Comedy",
"Director": "Joy Gohring",
"Writer": "Briana Lane",
"Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ##._V1_SX300.jpg",
"Metascore": "N/A",
"imdbRating": "8.2",
"imdbVotes": "5",
"imdbID": "tt1937109",
"Type": "movie",
"Response": "True"
}
}

Related

How to print this specific JSON in a Mat Table?

I have this specific JSON file I'm not allowed to change, which looks like this :
{
"computers" : {
"John" : {
"version" : "1.42.0",
"environment" : "Default",
"platform" : "x64",
"admin" : "true"
},
"Peter" : {
"version" : "1.43.6",
"environment" : "Default",
"platform" : "x64",
"admin" : "true"
},
"Eric" : {
"version" : "1.43.6",
"environment" : "Default",
"platform" : "x64",
"admin" : "false"
}
}
I use the JSON.parse() method to parse the file and I put it into a MatTableDataSource.
Problem is, when I need to display it in my MatTable, I can't really access it the way I want.
I have a column where I want to display all version parameters, so for this I can't say : this.dataSource.computers.????.version
Do you guys see where I'm getting at ? Do you have any idea of what I can do differently in order to solve this ?
Looking forward to reading you.
The Angular mat-table requires the input data to be in an array. First, we use Object.keys() to extract the keys, which will contain the list of names. Then, we can use Object.values() to other values within each key in array format. This is followed by mapping the above array objects with the name property from the list of names.
const data = {
"computers": {
"John": {
"version": "1.42.0",
"environment": "Default",
"platform": "x64",
"admin": "true"
},
"Peter": {
"version": "1.43.6",
"environment": "Default",
"platform": "x64",
"admin": "true"
},
"Eric": {
"version": "1.43.6",
"environment": "Default",
"platform": "x64",
"admin": "false"
}
}
};
const nameList = Object.keys(data.computers);
const dataList = Object.values(data.computers).map((obj, index) => {
obj['name'] = nameList[index];
return obj;
});
console.log(dataList);

How to create a custom intent and calling helper intent using Actionsdk?

Please find my action.json file content
{
"actions": [
{
"description": "Default Welcome Intent",
"name": "MAIN",
"fulfillment": {
"conversationName": "testapp"
},
"intent": {
"name": "actions.intent.MAIN",
"trigger": {
"queryPatterns": [
"talk to Developer"
]
}
}
},
{
"name": "BUY",
"intent": {
"name": "com.example.sekai.BUY",
"parameters": [{
"name": "color",
"type": "SchemaOrg_Color"
}],
"trigger": {
"queryPatterns": [
"find some $SchemaOrg_Color:color sneakers",
"buy some blue suede shoes",
"get running shoes"
]
}
},
"fulfillment": {
"conversationName": "testapp"
}
}
],
"conversations": {
"testapp": {
"name": "testapp",
"url": "https://us-central1-samplejs2-id.cloudfunctions.net/testApp",
"fulfillmentApiVersion": 2,
"inDialogIntents": [
{
"name": "actions.intent.CANCEL"
}
]
}
},
"locale": "en"
}
Please find my index.js file content
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {actionssdk} = require('actions-on-google');
const app = actionssdk({debug: true});
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
app.intent('com.example.sekai.BUY', (conv, input) => {
console.log("Inside custom intent");
conv.ask('<speak>Hi! <break time="1"/> ' +
' The color you typed is' +
`<say-as >${input}</say-as>.</speak>`);
});
app.intent('actions.intent.MAIN', (conv, input) => {
conv.ask('<speak>Hi! <break time="1"/> ' +
'You are entering into samplejs application by typing ' +
`<say-as >${input}</say-as>.</speak>`);
});
app.intent('actions.intent.CANCEL', (conv) => {
conv.close(`Okay, let's try this again later.`);
});
app.intent('actions.intent.TEXT', (conv, input) => {
if (input === 'bye') {
return conv.close('Goodbye!');
}
conv.ask('<speak>You said, ' +
`<say-as >${input}</say-as>.</speak>`);
});
//exports.app = app;
console.log("global----------->",global);
exports.testApp = functions.https.onRequest(app);
Whenever I call the custom intent "BUY" using any color, instead of calling my custom intent it is calling "intent.Text". How to fix this issue?
While creating cloud function I have select JavaScript option.
For creating a custom intent, is these much updates is need in action.json?
Is there any option for creating custom intent?
How to call this helper content in the js file?
app.intent('ask_for_place', (conv) => {
conv.ask(new Place(options));
});
Custom intents are only triggered as welcome intents for "deep linking". Once the conversation has started, all conversational intents will be reported as TEXT.
So for the intent com.example.sekai.BUY you defined in your actions.json file, and if your Action was named something like "super store", then the following invocation would trigger that intent:
Hey Google, ask super store to find some blue sneakers
but once the conversation had started, asking "find some blue sneakers" would trigger a TEXT intent.
The Actions SDK with actions.json is primarily intended for use by systems that provide the natural language processing and just want to get the text after it has been converted from speech.
If you want more sophisticated natural language processing, where each phrase in the conversation will trigger a user-defined Intent, take a look at Dialogflow.

How to Check a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})

AngularJS getting in trouble with my JSON

I have got a JSON object from my website:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”},
}
and AngularJS to manage the dynamic content but it doesn't seem to be working:
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function () {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function (data, status) {
$scope.people = data;
});
};
}
Here is a JSFiddle.
Can anybody help me with displaying data?
#qqruza to get the callback working properly in your jsfiddle.net/1zuteco7, change the url to this:
http://test.eventident.com/api/last_posts/siteid=&callpage=1&perpage=10&callback=JSON_CALLBACK
Notice the JSON_CALLBACK in the end. The rest of your app will still not work though cause you are not picking the right bindings from the returned data in your repeat directive. Try console.log(data) in the success function to click through the returned object and get to the right paths.
There were a number of issues with your JSON, I have resolved them.
It had different types of quotes in there. I have replaced them with ".
It now looks like this:
[{         
"ID": "100",
"role": {            
"subscriber": true         
},
"first_name": "Test",
"last_name": "Test2",
"custom_fields": {            
"job_title": "subscriber"         
},
}, {   
"ID": "102",
"role": {            
"subscriber": true         
},
"first_name": "Test 3",
"last_name": "Test 4",
"custom_fields": {            
"job_title": "testing"         
},       
}]
Also, you were not referencing the model fields correctly in your view.
Here is the updated working fiddle: http://jsfiddle.net/kmmmv83y/1/
You had a comma at the end of the last property, that will typically error everything out, the below JSON should work:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”}
}

How to get deeper in a JSON object using angularJS?

I am using AngularJs to get some information inside this JSON object, specifically the author's first and last name:
{
"bookid": "1",
"title": "Spring In Action",
"publisher": "Manning Publications Co.",
"isbn": "978-1-935182-35-1",
"owner": "Catalyst IT Services",
"publishyear": "2011",
"image": "C:/imagefolder/spring-in-action.jpg",
"description": "Totally revised for Spring 3.0, this book is a...",
"author": [
{
"authorid": "1",
"firstname": "Craig",
"lastname": "Walls",
"description": "Craig Walls has been professionally developing software for over 17 years (and longer than that for the pure geekiness of it). He is the author of Modular Java (published by Pragmatic Bookshelf) and Spring in Action and XDoclet in Action (both published by (...)"
}
],
"media": [
],
"tags": [
{
"tagid": "1",
"tagname": "Java"
},
{
"tagid": "5",
"tagname": "Spring"
}
],
"copies": [
{
"bookcopyid": "2",
"location": "Beaverton",
"status": "available"
}
]
}
The code I have right now is (which was provided by bosco2010 in this plunker (http://plnkr.co/edit/GbTfJ9)):
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL, scope) {
return $http.get(jsonURL).success(function (data, status) {
scope.data = data.author;
});
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
JsonSvc.read('data.json', $scope).then(function () {
$scope.nestedObj = $scope.data;
});
$scope.name = "world";
});
To get the first and last name, you'll need to reference author[0].firstname and author[0].lastname.
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL) {
return $http.get(jsonURL);
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
// The return object from $http.get is a promise. I used .then()
// to declare $scope.nestedObj after the http call has finished.
JsonSvc.read('data.json').then(function (data) {
console.log(data.data);
$scope.nestedObj = data.data.level1;
});
// ensure app is working
$scope.name = "world";
// Using nested obj within declared scope var doesn't work
// Uncomment below to break whole app
// Using nested obj in a function works but throws TypeError
// Declaring $scope.data.level1.level2 = [] first helps here
$scope.getLen = function () {
return $scope.nestedObj ? $scope.nestedObj.level2.length : ''; // return an empty string if the callback didn't happen yet
};
});
In short, it is incorrect to use both the success() function and also the then() function of the promise returned by the $htttp service.
Moreover, it is wrong to pass your scope as a parameter to your service and try to modify it there.
if you need to communicate between the service and a controller directly, you can use either $rootScope, $broadcat, or both.
I patched up your code, and now it works.
Plunk:
http://plnkr.co/edit/PlJZZn?p=preview