System Can't Find JSON file - javascript

I have a simple program I am writing that has 3 files:
1.an HTML file (index.html)
2.a Javascript file (app.js)
3.a JSON dataset (dataset.json)
All I want to do is get the browser to recognize the data and I can't do it.
My app.js file:
$(document).ready(function(){
$.getJSON('dataset.json', function(data){
console.log(data);
});
});
My dataset.json file:
[
{
"Gender": "Female",
"Height": 5'2,
"Weight": 100,
"Age": 25,
"Occupation": "Lawyer"
},
{
"Gender": "Male",
"Height": 5'9,
"Weight": 150,
"Age": 23,
"Occupation": "Student"
}
]
Any ideas? Am I missing something completely? On my index.html, all I have in the head is:
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>

You JSON file is invalid
"Height": 5'2, <-- that is not valid
"Height": 5'9, <-- that is not valid
Needs to be a string or a number
"Height": "5'2",
"Height": "5'9",

You have to open it with a live server, otherwise it won’t work (opening the index.html for example). You can use a VSCode Plugin (LiveServer) for that.

Related

JSON - Invalid Token

I watched a YouTube video trying to learn JSON for the first time. This is the example we did during the video, but at '[ I get an Invalid Token error when looking at the console. Sorry for the noob question! Thanks again.
<html>
<head>
<title>JSON Example</title>
</head>
<body>
<script type="text/javascript">
let companies =
'[
{
"name": "Big Corporation",
"numberOfEmployees": 10000,
"ceo": "Mary",
"rating": 3.6
},
{
"name": "Small Startup",
"numberOfEmployees": 3,
"ceo": null,
"rating": 4.3
}
]'
console.log(JSON.parse(companies))
((companies)[0].name)
</script>
</body>
</html>
The problem is not a JSON one but a JavaScript one. You have to use a particular syntax for multiline strings in JavaScript.
There are multiple ways of doing this but probably the simplest is to use backticks.
<html>
<head>
<title>JSON Example</title>
</head>
<body>
<script type="text/javascript">
let companies =
`[
{
"name": "Big Corporation",
"numberOfEmployees": 10000,
"ceo": "Mary",
"rating": 3.6
},
{
"name": "Small Startup",
"numberOfEmployees": 3,
"ceo": null,
"rating": 4.3
}
]`
console.log(JSON.parse(companies))
((companies)[0].name)
</script>
</body>
</html>
PS: As an aside you'll also get an error on the last line ((companies)[0].name) because the output of console.log isn't a function. Presumably you want another call to console.log

Using AngularJS to consume REST

I've made a REST api using Flask which gives a JSON response on http://localhost:5000/api/person giving the id,names and phone numbers of all the people in a SQLite database. http://localhost:5000/api/person/Name_of_person gives the JSON response corresponding to a person's name. I want to use AngularJS to consume the API so that I can output the names of all the people along with their phone numbers.
index.html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.id }} + ', ' + {{x.name }} + ',' + {{x.phone}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:5000/api/person").then(function (response) {
$scope.myData = response.data.objects;
});
});
</script>
</body>
</html>
Contents of http://localhost:5000/api/person
{
"num_results": 5,
"objects": [
{
"id": 24,
"name": "Name2",
"phone": "9999192938"
},
{
"id": 23,
"name": "Name3",
"phone": "9999192938"
},
{
"id": null,
"name": "Name4",
"phone": "9999192938"
},
{
"id": 21,
"name": "Name5",
"phone": "9999192938"
},
{
"id": null,
"name": "Name6",
"phone": "9999192938"
}
],
"page": 1,
"total_pages": 1
}
I am pretty sure my syntax is correct but I am getting no output for index.html. Can anyone please explain where I am going wrong? Is it maybe because it is on a local server and is unable to retrieve the data?
Please test the api by REST client, if the API returns proper result.
If you are having problem in running the application, please test using firefox browser. For chrome you need to serve the index.html through any server as it blocks file:/// protocol and needs http:// to run properly.
Make sure your API supports CORS. You have to set it in API end (see Flask docs) or else you can use CORS plugin for chrome.
If still problem persists there might be any logical/syntactical error. Please paste/share screenshot of your browser console.

Passing Json data from Controller to View in Angular JS to build a table

Trying to get the certain fields to display, ideally in a table (headings, rows & columns). And looking for a best way find fields in a Json feed. I tried using the controller to find the fields then pass that data to the view in the HTML.
Is there something wrong in the controller with respect to the Json? the fields are empty. Seems like nothing is passed from the controller to the view ? This is what I tried:
<!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>
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$scope.result = {
"data": {
"transactionList": [{
"barcode": "52905819992681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "12Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}, {
"barcode": "52905819592681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "23Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}]
}
}
};
$scope.elements = $scope.result.data.transactionList.map(function (res) {
var e = {};
e.transTypeId = res.transTypeId;
e.userId = res.userId;
e.storeId = res.storeId;
return e;
});
});
</script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from the JSON feed</h1>
<ul>
<li ng-repeat="e in elements">
{{ e.transTypeId}}: {{ e.userId }}, {{ e.storeId }}
</li>
</ul>
</body>
</html>
You have a extra } in your $scope.result. It should be like:
$scope.result = {
"data": {
"transactionList": [{
"barcode": "52905819992681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "12Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}, {
"barcode": "52905819592681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "23Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}]
}
};
// get rid of this};
Here is working plunkr
Perhaps a }; too many?
Automatic indentation usually makes those kinds of errors apparent.
Have you tried to use ng-model="...", it gives you the opportunity to overwrite an attribute or to show it. You can try it with
<input type="number" ng-model="someID" disabled="disabled">
*disabled if u need readOnly on that field.
and see how it works, maybe it can help you out.
regards
I may be wrong, but you are trying to read json data directly without parsing it?
MDN JSON.parse()
Also it would be nice if you upload your code on something like http://jsfiddle.net
This way people can test it out.

Load external JSON file in PaperJS

I thought this would be really simple to do with:
project.importJSON('structures.json')
Unfortunately this gives me:
JSON Parse error: Unexpected identifier "structures"
This "structures" must come from the JSON file structures.json itself which looks like this:
{
"structures": [
{"name":"shed", "width": 4, "height": 3, "depth": 5},
{"name": "house", "width": 6, "height": 7, "depth": 5},
{"name": "factory", "width": 4, "height": 3.5, "depth": 6.5,
"depth_sub_1": 5.5,
"depth_sub_2": 4.5 }
]
}
Any ideas on how to make this work? I'd rather not use jQuery for this.
Edit
So it seems to me that using importJSON can only work when the JSON is an actual Paper object. The same error keeps on occurring.
What's the alternative? I want my external 'structural' data in what is basically a JavaScript file. Should I use the regular route for doing so?
My html looks something like this:
<head>
<script type="text/javascript" src="../../assets/javascript/paper-full.js"></script>
<script type="text/paperscript" src="I/a_view_on_my_structures.js" canvas="phase-I"></script>
</head>
<body>
<canvas id="phase-I" resize="true"></canvas>
</body>
You should stringify your data.
var structures = {
"structures": [
{"name":"shed", "width": 4, "height": 3, "depth": 5},
{"name": "house", "width": 6, "height": 7, "depth": 5},
{"name": "factory", "width": 4, "height": 3.5, "depth": 6.5,
"depth_sub_1": 5.5,
"depth_sub_2": 4.5 }
]
}
project.importJSON(JSON.stringify(structures))
if you json data is in a different file you should read that file first
This is how you read a file
synchronously
var client = new XMLHttpRequest();
client.open('GET', 'path/to/your/file', false);
client.onreadystatechange = function() {
//your data is in client.responseText
console.log(client.responseText);
}
client.send(null);
asynchronously
var client = new XMLHttpRequest();
client.open('GET', 'path/to/your/file');
client.onreadystatechange = function() {
//your data is in client.responseText
console.log(client.responseText);
}
client.send();
notice that when you do this, you don't need to stringify your data, because you read it as a text, so you just have to pass the client.responseText content to the importJSON function

Parse local JSON file with jQuery and Javascript

I'm trying to parse a JSON file located on my computer. I want to parse it. The JSON file has this structure:
{
"sites": {
"site": [
{
"id": "01",
"name": "Sito 1",
"src": "localhost/root/coupon/sito1",
"expiryDate": "29 Ago 2013"
},
{
"id": "02",
"name": "Sito 2",
"src": "localhost/root/coupon/sito2",
"expiryDate": "30 Ago 2013"
},
{
"id": "Sito 3",
"name": "Sito 3",
"src": "localhost/root/coupon/sito2",
"expiryDate": "31 Ago 2013"
}
]
}
}
In my html I import the jQuery library and I made a function that will load when the page is loaded. The code is below:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<title>Lista coupon</title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8">
function loadJson() {
window.alert("Carico il contenuto del file JSON per popolare la lista");
$(document).ready(function()
{
$.getJSON('data.json', function(json) {
console.log(json);
});
});
}
</script>
</head>
<body onload="loadJson();">
<div id="header">
<h1>Lista coupon salvati</h1>
</div>
<div id="content">
<p>Di seguito trovi tutte le promozioni salvate</p>
</div>
<div id="footer">
</div>
</body>
</html>
Now I saw on firebug console that it can read correctly the JSON file, but I don't know how to parse this JSON. I searched in google, but I found a lot of example that use a remote JSON. Can you help me to understand how to parse a local JSON file?
Thank you
PS: note the site I post on here it's made for mobile browser.
getJSON will parse it for you.
Just remove the var obj = $.parseJSON(json); line (since that will stringify the object and try to parse it as JSON (which it won't be)).
I don't think you need to parse the json. It will automatically parse the json since you are using $.getJSON().

Categories

Resources