when i try to put json fetched object from console to html i get error saying object in html
i fetched object from url to console but when i try to put in h1 or p it gets an error, i know i miss something just dont know what
var questionP = document.getElementById("question");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'quiz.json');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
document.getElementById('question').innerHTML=ourData.quiz.q1;'
};
ourRequest.send();
{
"quiz": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
},
"q2": {
"question": "'Namaste' is a traditional greeting in which Asian language?",
"options": [
"Hindi",
"Mandarin",
"Nepalese",
"Thai"
],
"answer": "Hindi"
}}}
I'm working on a lambda project and getting data from an API inside the function which looks like this
{ "Title": "300", "Year": "2006", "Rated": "R", "Released": "09 Mar 2007", "Runtime": "117 min", "Genre": "Action, Fantasy, War", "Director": "Zack Snyder", "Writer": "Zack Snyder (screenplay), Kurt Johnstad (screenplay), Michael B. Gordon (screenplay), Frank Miller (graphic novel), Lynn Varley (graphic novel)", "Actors": "Gerard Butler, Lena Headey, Dominic West, David Wenham", "Plot": "King Leonidas of Sparta and a force of 300 men fight the Persians at Thermopylae in 480 B.C.", "Language": "English", "Country": "USA, Canada, Bulgaria", "Awards": "17 wins & 45 nominations.", "Poster": "https://m.media-amazon.com/images/M/MV5BMjc4OTc0ODgwNV5BMl5BanBnXkFtZTcwNjM1ODE0MQ##._V1_SX300.jpg", "Ratings": [ { "Source": "Internet Movie Database", "Value": "7.7/10" }, { "Source": "Rotten Tomatoes", "Value": "60%" }, { "Source": "Metacritic", "Value": "52/100" } ], "Metascore": "52", "imdbRating": "7.7", "imdbVotes": "691,774", "imdbID": "tt0416449", "Type": "movie", "DVD": "31 Jul 2007", "BoxOffice": "$210,500,000", "Production": "Warner Bros. Pictures", "Website": "http://300themovie.warnerbros.com/", "Response": "True" }
I've tried dot notation, indexing all sorts but no matter what I try, the console log just comes out with
2019-06-14T18:33:46.394Z ecc5d247-6475-464e-8dd7-bec310d98c4a INFO undefined
Has anyone else had the same issue before with lambda and lex?
Thanks
const https = require('https')
let url = "http://www.omdbapi.com/?t=300&r&apikey=3ecc35a"
let reply;
const http = require('http')
let test;
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log(body);
reply = JSON.parse(body);
});
});
This currently produces a perfectly good JSON in the console but it's impossible to actually extract anything. I've tried reply.Year, reply["Year"], reply.[0].Year almost any combination I can think off.
Full Code
'use strict';
'use fetch';
// Close dialog with the customer, reporting fulfillmentState of Failed or Fulfilled ("Thanks, your pizza will arrive in 20 minutes")
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}
// --------------- Events -----------------------
function dispatch(intentRequest, callback) {
console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
const sessionAttributes = intentRequest.sessionAttributes;
//const film = intentRequest.currentIntent.film;
const film = intentRequest.currentIntent.slots.film.toString();
console.log(intentRequest.currentIntent.slots.film.toString());
const https = require('https')
let url = "http://www.omdbapi.com/?t=300&r&apikey=3ecc35a"
let reply;
const http = require('http')
let test;
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log(body);
reply = JSON.parse(body);
});
});
//const rating = reply.imdbRating;
console.log(reply);
callback(close(sessionAttributes, 'Fulfilled',
{'contentType': 'PlainText', 'content': `The film ${film} has a rating of `}));
}
// --------------- Main handler -----------------------
// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
exports.handler = (event, context, callback) => {
try {
dispatch(event,
(response) => {
callback(null, response);
});
} catch (err) {
callback(err);
}
};
I tried to reproduce the issue with that code and got the following error
Response:
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'name' of undefined",
"trace": [
"TypeError: Cannot read property 'name' of undefined",
" at dispatch (/var/task/index.js:20:112)",
" at Runtime.exports.handler (/var/task/index.js:65:9)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:63:25)",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
Line 20 of index.js for me is:
console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
However when using the test event in the question event.currentIntent doesn't exist and the name property of the event object doesn't exist either.
If I remove part of the console.log statement and change it to reference the Title attribute which exists in the test event I get:
console.log(`request received for Title=${intentRequest.Title}`);
INFO request received for Title=300
Seems like the function's code is referencing attributes fine but the function's just not receiving it's expected event objects.
HTH
-James
I'm trying to get the first top-track preview url from an artist but everytime I do the search it returns a broken json. I can parse it as a string to get what I need but a json would be a lot easier. Here is my code:
const https = require('https');
var open = require('open')
function songError(){
console.log('There was some kind of error fetching your artist ;(');
}
function getTopSong(p_id){
https.get('https://api.spotify.com/v1/artists/'+p_id+'/top-tracks?country=BR', function(res){
res.on("data", function(chunk){
var json = JSON.parse(chunk.toString('utf8'));
console.log(json);
});
});
}
function getArtistID(p_name) {
https.get('https://api.spotify.com/v1/search?q='+encodeURI(p_name)+'&type=artist', function(res){
res.on("data", function(chunk) {
var json = JSON.parse(chunk.toString('utf8'));
if(json['artists']['items'][0]['id'] != undefined || json['artists']['items'][0]['id'] != null){
console.log('id: ',json['artists']['items'][0]['id']);
getTopSong(json['artists']['items'][0]['id']);
}else
{
songError();
}
});
});
}
getArtistID("rage against the machine");
There seems to be an error in line 329:
undefined:329
"available_markets" : [ "AR", "AU", "AT", "BE", "BO", "BR", "BG", "CA", "CL", "CO", "CR", "CY", "CZ", "DK", "DO", "DE", "EC", "EE", "SV", "FI", "FR", "GR", "
My question is, am I doing something wrong or is it really broken?
Thanks!
I could curl it without any problems at least:
$ curl -s 'https://api.spotify.com/v1/artists/2d0hyoQ5ynDBnkvAbJKORj/top-tracks?country=BR' | python -mjson.tool | tail
"id": "25CbtOzU8Pn17SAaXFjIR3",
"name": "Take The Power Back - Remastered",
"popularity": 58,
"preview_url": "https://p.scdn.co/mp3-preview/b44e8f96a219871587d0559970ca5dce71c891f2",
"track_number": 3,
"type": "track",
"uri": "spotify:track:25CbtOzU8Pn17SAaXFjIR3"
}
]
}
I don't know much about nodejs, but don't you need to concatenate all callbacks to res.on("data"?
https://nodejs.org/api/http.html#http_http_request_options_callback
https.get('https://api.spotify.com/v1/artists/' + p_id + '/top-tracks?country=BR', function(res) {
var body = [];
res.on("data", function(chunk) {
body.push(chunk);
});
res.on("end", function() {
var json = JSON.parse(Buffer.concat(body).toString("utf8"));
console.log(json);
});
});
If the response is long and Spotify's servers decides to send the response back chunked transfer encoding, then the nodejs http module probably splits the response up as well.
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"
}
}