Parse local JSON file with jQuery and Javascript - 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().

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

Dynatable Implementation

I am attempting to learn some jQuery and javascript and have a neat project to try. It involves pulling data from a JSON file and displaying it in a table form, based on date. I've found Dynatable which seems to do what I want, but I keep getting an "unexpected end of JSON input" error. I am using the same syntax as in the example given on the Dynatabe page, but it does not return any records. Any help would be appreciated, as I'm sure I'm missing something simple. The JSON file is named json-records.json
[
{
"band": "Weezer",
"song": "GA Scorcho"
},
{
"band": "Chevelle",
"song": "Family System"
},
]
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="./jspkg-archive/jquery.dynatable.js"></script>
<script src="json-records.json"></script>
<style src="./jspkg-archive/jquery.dynatable.css"></style>
</head>
<body>
<table id="my-final-table">
<thead>
<th>Band</th>
<th>Song</th>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
$(document).ready( function(){
$('#my-final-table').dynatable();
});
var $records = $('#json-records'),
myRecords = JSON.parse($records.text());
$('#my-final-table').dynatable({
dataset: {
records: myRecords
}
});
</script>
</body>
</html>
You have a stray ',' in your JSON file
[
{
"band": "Weezer",
"song": "GA Scorcho"
},
{
"band": "Chevelle",
"song": "Family System"
}, <--- Here
]

dynatable not creating table from remote JSON

Here's feature-table.JSON in the same directory as the HTML file:
[
{
"band": "Weezer",
"song": "El Scorcho"
},
{
"band": "Chevelle",
"song": "Family System"
}
]
Here's my HTML file:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.11.1.min.js">
<script type="text/javascript" src="jquery.dynatable.js"></script>
<script type="text/javascript">
$.getJSON("feature-table.JSON", function(data) {
alert(data);
$("#feature-table").dynatable({
dataset: {
records: data
}
});
});
</script>
</head>
<body>
<table id="feature-table">
<thead>
<th>band</th>
<th>song</th>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
The alert pops up with the correct JSON data so i know it's finding it. I've tried: version 2 of jQuery, uploading and using URLs of the js files to make sure the files are in the right place, $.ajax but then $.getJSON after reading Load remote JSON from Dynatable, and various other things. I'm out of ideas. What am I overlooking?
I discovered I needed to have my JavaScript inside $(document).ready(function(){...}).
Hope this helps.
Did you also include the metadata as per the documentation for the JSON array.
{
"records": [
{
"someAttribute": "I am record one",
"someOtherAttribute": "Fetched by AJAX"
},
{
"someAttribute": "I am record two",
"someOtherAttribute": "Cuz it's awesome"
},
{
"someAttribute": "I am record three",
"someOtherAttribute": "Yup, still AJAX"
}
],
"queryRecordCount": 3,
"totalRecordCount": 3
}

Why I have to access JSON in a special way in Angular? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I'm working on AngularJs tutorial and I would like to access JSON. I do not understand why in tutorial they use [] to access JSON. When user click on the "a tag" it will put airport.code into setAirport function and get the currentAirport.name back
Here is the code:
HTML:
<html ng-app>
<head>
<title>Demo</title>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/controllers/app.js"></script>
</head>
<body>
<div ng-controller="AppCtrl">
<h1>AngulAir</h1>
<ul>
<li ng-repeat="airport in airports">
<a href="" ng-click="setAirport(airport.code)">
{{airport.code}} - {{airport.city}}
</a>
</li>
</ul>
<p ng-show="currentAirport">Current Airport : {{currentAirport.name}}</p>
</div>
and this is the JS code:
function AppCtrl ($scope) {
$scope.airports = {
"PDX": {
"code": "PDX",
"name": "Portland International Airport",
"city": "Portland",
"destinations": [
"LAX",
"SFO"
]
},
"STL": {
"code": "STL",
"name": "Lambert-St. Louis International Airport",
"city": "St. Louis",
"destinations": [
"LAX",
"MKE"
]
}
};
$scope.currentAirport = null;
$scope.setAirport = function (code){
$scope.currentAirport = $scope.airports[code];
};
}
you can see in the last statement ---> $scope.currentAirport = $scope.airports[code]; it use [] to access the JSON. I do not understand why it is used this way. I tried to experiment in another situation and it seems to work differently, here is my experiment:
HTML:
<html>
<head>
<title>hello world</title>
</head>
<body>
</body>
<script type="text/javascript" src=jsfile.js></script>
<script type="text/javascript">
alert(airports[code]);
</script>
JS file:
airports = {
"PDX": {
"code": "PDX",
"name": "Portland International Airport",
"city": "Portland",
"destinations": [
"LAX",
"SFO"
]
},
"STL": {
"code": "STL",
"name": "Lambert-St. Louis International Airport",
"city": "St. Louis",
"destinations": [
"LAX",
"MKE"
]
}
};
and I get this on my browser "ReferenceError: Can't find variable: code" WHY? the JSON access way of this statement -----> $scope.currentAirport = $scope.airports[code]; is not equal to this statement -----> alert(airports[code]); ?????
why in the second case I can't use [] ? anyone knows please tell me
In the first example:
$scope.setAirport = function (code){
$scope.currentAirport = $scope.airports[code];
};
code is passed to the function and they use it reference the airport code in the airport object.
In your example:
alert(airports[code]);
code is undefined.
You need to define code, or manually pass an airport code to it.

Parse and iterate JSON with multiple headers

I'm able to iterate through a simple json loop, but actually the API i'm working with returns a response with multiple headers and I tried different methods to access the results objects but still not working, the response looks like this:
"meta": {
"name": "openaq-api",
"license": "CC BY 4.0",
"website": "https://docs.openaq.org/",
"page": 1,
"limit": 100,
"found": 1544
},
"results": [
{
"city": "Buenos Aires",
"country": "AR",
"locations": 4,
"count": 8064
},
{
"city": "Gemeinde Wien, MA22 Umweltschutz",
"country": "AT",
"locations": 21,
"count": 136958
},
What I'm trying to do is to access results then iterate with cities infos, my runnable attempts:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
<title>Open AQ API</title></head>
<body>
<div id="data"></div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script type="text/javascript">
var url = "https://api.openaq.org/v1/cities";
$.getJSON(url, function (data) {
var json = data
$.each($.parseJSON(json), function() {
alert(results.this.city);
});
});
</script>
</body>
</html>
Attempt 2 :
// data[i]
$.each(data, function(i, item){
$('#data').append(
$('<h1>').text(item.results.city),
$('<div>').text(item.results.country),
$('<h6>').text(data[i].results.count),
);
});
This works just fine, try this instead for your jQuery.
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
<title>Open AQ API</title></head>
<body>
<div id="data"></div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script type="text/javascript">
var url = "https://api.openaq.org/v1/cities";
$.getJSON(url, function (data) {
$.each(data.results, function(i, result) {
console.log(result.city);
});
});
</script>
</body>
</html>
Kindly update below logic, data will give full response, SO you have to take results from data like $.parseJSON(json).results and then run for each loop as shown below.
$.each(json.results, function(index,value) {// json is same as data as per your code
alert(value.city);
});

Categories

Resources