Simple javascript to process JSON API response not working - javascript

I am new to javascript and am trying to process a simple JSON response from an API. But when i run the following code i get nothing.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('http://76.233.189.148:5000/index.json', function(result){
document.write(result.datasets);
});
});
</script>
</head>
<body>
</body>
</html>
I know the API is working since from:
http://76.233.189.148:5000/index.json
it returns:
{
"datasets": [
{
"id": "20150803-183949-44df",
"name": "Train0010",
"status": "Done"
}
],
"models": [
{
"id": "20150803-184058-97ff",
"name": "train0010_alex",
"status": "Done"
}
]
}
What am i doing wrong here?

Related

DataTables Jquery Ajax Object not finding array columns

I'm trying to use jquery.dataTables with an Ajax data source to pull json data into a html table.
I'm facing an issue where it's not able to find the data I'm looking for in the JSON response and I'm struggling to find where my issue lies. I'm getting an undefined error as it's not able to match the data columns I requested.
In the Snipped-I removed the URL but here's a sample of the object structure returned.
{
"success": true,
"result": [
{
"type": "gift",
"name": "Gift",
"rewards": [
{
"name": "Item Name",
"image_url": "https://xxx.jpg",
"minimum_display_price": "500+ bucks",
"description": {
"text": "text here",
"html": "html here"
},
"disclaimer_html": "disclaimer",
"warning": null,
"denominations": [
{
"id": "5ca1737f1sdasdsadsad2cb5f004cc0d564",
"name": "Name",
"price": 500,
"display_price": "500",
"available": true
}
]
}
]
}
]
}
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "myurlishere",
"columns": [
{ "result[0]": "name" }
//{ "result": "rewards.name"}
// {"data": "name"}
]
} );
} );
<script language="JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.colVis.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.print.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.bootstrap.min.js" type="text/javascript"></script>
<script language="JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js" type="text/javascript"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
</tr>
</tfoot>
</table>
Looks like you have some nested data objects and while it might be possible to deal with this directly within DataTable it's likely easier to pre-process the data before handing it off to DataTable for rendering. This would convert your nested data into a flat array of reward objects, which should make rendering it easier.
(async function() {
const rawData = await fetch("your_url").then(data => data.json());
const finalData = rawData.result.map(category => category.rewards).flat(1);
$("#example").DataTable({
data: finalData,
columns: [{ data: "name" }]
});
})();
Might be you need to change your code , just check following way,
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "myurlishere",
"columns": [
{ "data": "name" },
{ "data": "rewards[, ].name" },
{ "data": "rewards[, ].image_url" },
{ "data": "rewards[, ].description.text" },
{ "data": "rewards[, ].denominations[,].name" },
]
} );
} );

Grunt mustache_render won't render HTML file correctly

I am using https://www.npmjs.com/package/grunt-mustache-render to render a HTML file using a layout file and json file.
Here is the Grunt task:
mustache_render: {
json_data: {
files: [
{
data: 'output.json',
template: 'test.mustache',
dest: 'tmp/hello_json.html'
}
]
}
}
Output JSON looks like this:
[
{
"name": "John Doe",
"age": "30"
},
{
"name": "Alex Len",
"age": "27"
},
{
"name": "Debbie John",
"age": "36"
}
]
test.mustache looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Mustache Sample</title>
</head>
<body>
<h2>Titles</h2>
<ul id="talktitles">
<script id="speakers-template" type="text/template">
{{#options}}
<li>{{{name}}}, {{{age}}}</li>
{{/options}}
</script>
</ul>
</body>
</html>
When I run grunt it created the tmp/hello_json.html file but the values are not populated. It looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Mustache Sample</title>
</head>
<body>
<h2>Titles</h2>
<ul id="talktitles">
<script id="speakers-template" type="text/template">
</script>
</ul>
</body>
</html>
What am I doing wrong here?
Your output.json doesn't conform with template. Template waits options value in json file, but there is not such key.
Correct output json should be like this one:
{
options: [{
"name": "John Doe",
"age": "30"
}, {
"name": "Alex Len",
"age": "27"
}, {
"name": "Debbie John",
"age": "36"
}]
}
Addition
Also you have an ability to refer root of the json file with .
So you can change your template part to this
{{#.}}
<li>{{{name}}}, {{{age}}}</li>
{{/.}}

Output page blank while fetching data from JSON file in AngularJS

I have just started learning angularjs, I'm trying to load data from my json file on view. json file has a list of houses. But does not get showed on my view when I load the index.html file.
Data.json
[
{
"type": "Condo",
"price": 220000,
"address": "213 Grove Street",
"description": "Excellent place! Really nice view!"
},
{
"type": "House",
"price": 410500,
"address": "7823 Winding Way",
"description": "Beautiful home with lots of space for large family."
},
{
"type": "Duplex",
"price": 395000,
"address": "834 River Lane",
"description": "Great neighourhood and lot's of nice green space."
},
]
cribsFactory.js
angular
.module('ngCribs')
.factory('cribsFactory', function($http) {
function getCribs() {
return $http.get('data/data.json');
}
return {
getCribs: getCribs
}
});
cribsController.js
angular
.module('ngCribs')
.controller('cribsController', function($scope, cribsFactory) {
$scope.cribs;
cribsFactory.getCribs().success(function(data) {
$scope.cribs = data;
}).error(function(error) {
console.log(error);
});
});
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ng-cribbs</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body ng-app="ngCribs" ng-controller="cribsController">
<div class="well" ng-repeat="crib in cribs">
<h3>{{ crib.address }}</h3>
<p>
<strong>Type: </strong>{{ crib.type }}</p>
<p>
<strong>Description: </strong>{{ crib.description }}</p>
<p>
<strong>Price: </strong>{{ crib.price | currency }}</p>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"/>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.3/ui-bootstrap.min.js"/>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.3/ui-bootstrap-tpls.min.js"/>
</script>
<script src="app.js"/>
</script>
<script src="scripts/cribsController.js"/>
</script>
<script src="scripts/cribsFactory.js"/>
</script>
</html>
I'm trying to run the above code in htdocs folder of XAMPP. The folder structure is in the screen shot below.
The json file is inside the data folder and the files cribsFactory.js & cribsController.js are in scripts folder. When i type the URL "http://localhost/ng-cribbs/" in Firefox the output is a completely blank page with no error message of any sort hence the difficulty in debugging.
I was able to load data using an array but facing problem while using JSON file.. Can't understand what I'm doing wrong. Please help!!
Your json data was not valid, validate any json data before and you can use the below corrected json. Hope it helps! validate json here
[{
"type": "Condo",
"price": 220000,
"address": "213 Grove Street",
"description": "Excellent place! Really nice view!"
}, {
"type": "House",
"price": 410500,
"address": "7823 Winding Way",
"description": "Beautiful home with lots of space for large family."
}, {
"type": "Duplex",
"price": 395000,
"address": "834 River Lane",
"description": "Great neighourhood and lot's of nice green space."
}]
Your http call gives you a json string, you should convert it to a javascript array like so: $scope.cribs = JSON.parse(data)

AngularJS rendering from deeply nested jsonp

I am new to JSON and also AngularJS. I'm trying to access data elements in a deeply nested remote json file. I can manage to render the whole JSON results in my view. However, I can't seem to target the elements that are in an array deep inside the JSON. It's from Yahoo Currency.
This is my controller and view that renders the entire JSON file:
controller
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
view
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="row in data">
{{ data }}
</li>
</ul>
</body>
</html>
I tried writing the controller like this:
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
var pair = { name };
// $scope.data = data;
if(data) {
if (data.results) {
pair.name = data.results.list.resources[0].resource.fields.name;
}
}
});
});
But that doesn't work. Here is the JSON (partial) .. I'm trying to access the "name", "price", and "utctimestamp" fields for each resource:
{
"query": {
"count": 1,
"created": "2015-11-07T05:42:03Z",
"lang": "en-US",
"diagnostics": {
"publiclyCallable": "true",
"url": {
"execution-start-time": "0",
"execution-stop-time": "23",
"execution-time": "23",
"content": "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
},
"user-time": "25",
"service-time": "23",
"build-version": "0.2.311"
},
"results": {
"list": {
"meta": {
"type": "resource-list",
"start": "0",
"count": "173"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/KRW",
"price": "1152.994995",
"symbol": "KRW=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "SILVER 1 OZ 999 NY",
"price": "0.068046",
"symbol": "XAG=X",
"ts": "1446850711",
"type": "currency",
"utctime": "2015-11-06T22:58:31+0000",
"volume": "100"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/VND",
"price": "22364.000000",
"symbol": "VND=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
...
For what it's worth, jsonp seems to return some kind of xml-looking stuff when I append the callback=JSON_CALLBACK to the url, like this:
JSON_CALLBACK({"query":{"count":"1","created":"2015-11-07T16:08:29Z","lang":"en-US"},"results":["<list><meta><type>resource-list</type><start>0</start><count>173</count></meta><resources><resource><classname>Quote</classname><fields><name>USD/KRW</name><price>1152.994995</price><symbol>KRW=X</symbol><ts>1446900900</ts><type>currency</type><utctime>2015-11-07T12:55:00+0000</utctime><volume>0</volume></fields></resource></resources><resources><resource><classname>Quote</classname><fields><name>SILVER 1 OZ 999 NY</name><price>0.068046</price><symbol>XAG=X</symbol><ts>1446850711</ts><type>currency</type><utctime>2015-11-06T22:58:31+0000</utctime><volume>100</volume></fields></resource></resources><resources><resource>
...
Is there a problem with how I'm using JSONp? I'm getting the data set rendered to my view (above) but it's all in the funky xml syntax. How to go about grabbing the 3 values I need from that to an array and rendering in a <ul>??
You can use your original controller, you only had problems in the view. It would work if you substitute it by this one:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="res in data.query.results.list.resources">
{{ res.resource.fields.name }}: {{ res.resource.fields.price }}, {{ res.resource.fields.utctime }}
</li>
</ul>
</body>
</html>
Here is the Plunker using your JSON example: http://plnkr.co/edit/wzF5t9dTZt49n5eq9N1L?p=preview

How to load json data using AJAX call

I want to load JSON data into HTML file.
Problem is, it does not load json data and when I add error event then it gives me error alert for error object. Please guide me how I could resolve this issue. even, I could not find any specific alert to identiy the error. how to resolve this ? Is there any way to get actual error while working with jquery/ajax ?
Below is my html file which has jquery call to json data with html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/jquery-ui-1.8.20.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn382").click(function () {
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("car-sale.json", function (data) {
var html = [];
alert('result');
});
});
});
</script>
</head>
<body>
<input type="submit" id="btn382" />
</body>
</html>
JSON file is as follow:
[{
"Manufacturer": "Toyota",
"Sold": 1200,
"Month": "2012-11"
}, {
"Manufacturer": "Ford",
"Sold": 1100,
"Month": "2012-11"
}, {
"Manufacturer": "BMW",
"Sold": 900,
"Month": "2012-11"
}, {
"Manufacturer": "Benz",
"Sold": 600,
"Month": "2012-11"
}, {
"Manufacturer": "GMC",
"Sold": 500,
"Month": "2012-11"
}, {
"Manufacturer": "HUMMER",
"Sold": 120,
"Month": "2012-11"
}]
in the page header you should define this
<script src="car-sale.json"></script>
i check this with a firefox and its working fine check this with firefox
$.getJSON('car-sale.json', function (data) {
$.each( data, function( key, val ) {
console.log(val.Manufacturer );
});
});

Categories