Access json data from external file - javascript

I am trying to load/read data from a local json file using JQuery/Javascript. Everything I have tried so far is throwing me CORS policy error. I don't know how to resolve this.
<html>
<body>
<div>
Fetch JSON
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#fetch').click(function() {
$.getJSON('music.json', function(data) {
albums = data['Albums']
console.log(albums)
})
});
})
</script>
</body>
</html>
Json file -
{
"Albums": [{
"albumName": "Desire",
"artist": "Bob Dylan"
},
{
"albumName": "Live in London",
"artist": "Leonard Cohen"
},
{
"albumName": "Abbey Road",
"artist": "The Beatles"
},
{
"albumName": "Blackstar",
"artist": "David Bowie"
}
]
}
How to get this running?

You should run your project on the web server, in this case, you can do this:
data.json
{
"albums": [
{
"name": "First Album",
"artist": "Leonard Cohen"
}
]
}
in html or js file:
fetch('http://127.0.0.1:5500/data.json')
.then(response => response.json())
.then(json => console.log(json))
in this case, my webserver local address is http://127.0.0.1:5500

Related

Patch data fetched from API

I'm a beginner and trying to create a practice project. I'm trying to "patch" a data fetched from an API.
My json file looks like this:
{
"classes": [
{
"title": "Office Syndrome",
"length": "60 Minutes",
"instructor": "A. W.",
"difficulty": "Intermediate",
"description": "Suitable for people who are always constantly inactive working in front of computers.",
"availableSpot": "10",
"id": 1
},
{
"title": "Digestive Flow",
"length": "60 Minutes",
"instructor": "MJ",
"difficulty": "Beginners",
"description": "Good for digestion",
"availableSpot": "8",
"id": 2
}
]
I'm trying to create a functionality where the class is bookable where the availableSpot will be decreased by 1 after each booking.
My handleBook function currently looks like this:
const handleBook = (index) => {
setSelectedYogaClass(true);
if (selectedYogaClass === index) {
fetch("http://localhost:8000/classes", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ availableSpot: data.availableSpot - 1 }),
})
.then((res) => {
if (!res.ok) {
throw Error("Sorry, something went wrong");
}
})
.then((res) => {
console.log(res);
})
.catch((err) => {
setBookingError(err);
});
}
console.log(selectedYogaClass);
setModalIsOpen(false);
};
And this is how I am calling the function
<button
key={index}
onClick={() => handleBook(index)}
className="button button--outline"
>
Yes
</button>
However, I am getting a 404 error and am wondering what the problem is?
Could anyone point out what I am doing wrong?
Thank you so much in advance!
You need to specify specific resource when you use plural routes like http://localhost:8000/classes/:id.
If you want to update(PATCH) the availableSpot field of class with id 1, you should use http://localhost:8000/classes/1
An working example

Issues adding sessions and information to the Google Fit REST Api using JS

So I am reasonably new to using API's with Js but I am struggling a lot to understand how the Google Fit API works. I am attempting to add a new Workout's data to the API by adding a session and some data for the intensity (heart points) of the session. I can get the session to appear correctly but run into constant errors when I try to create a dataSource and add a point to it for the session. It would be greatly appreciated if someone could help me to fix my code to achieve this or could direct me to a more thorough example of similar code as the API docs don't seem to be too well detailed with examples etc. Thanks in advance.
Here's the 3 api calls that I have written so far, one for creating the DataSource, one for the DataPoint and one for the Session. The session works correctly and adds a session of 1 hr for the correct activity but I am unable to get any of the other API requests to work.
Data Source :
``gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {"field":[{
"format": "floatPoint",
"name": "com.google.heart_minutes"
}],
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000019",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
``
Data Point :
``
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:292824132082:op:6:1000019",
"userId": "me",
"datasetId": "1592087806561000000-1592287806561000000",
"resource": {
"minStartTimeNs": "1592087806561000000",
"maxEndTimeNs": "1592287806561000000",
"dataSourceId": "raw:com.google.heart_minutes:292824132082:op:6:1000019",
"point": [
{
"startTimeNanos": "1592087806561000000",
"endTimeNanos": "1592287806561000000",
"value": [
{
"fpVal": 89.1
}
],
"dataTypeName": "com.google.heart_minutes"
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
``
Session :
``gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": "someSessionId19",
"id": "someSessionId19",
"name": "Awesome Workout19",
"description": "A very intense workout",
"startTimeMillis": new Date().getTime() - 3600000,
"endTimeMillis": new Date().getTime(),
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": 3600000
}).then((res) => {console.log(res)});
console.log('res')
//request.execute((res) => {console.log(res);console.log('executrd')})
console.log(auth2.currentUser.get().getBasicProfile().getGivenName());
var request2 = gapi.client.fitness.users.sessions.list({
"userId":"me"
}).then((res) => {console.log(res)})
``
Error message
{message: "Unable to fetch DataSource for Dataset: raw:com.google.heart_minutes:292824132082:op:6:1000019", domain: "global", reason: "invalidArgument"}
It looks like it could be that you're trying to pass in the wrong fields for the data type: if you want to use a standard data type (like com.google.heart_minutes), you should either pass the exact fields of the standard data type (the field should be called "intensity"); or just pass the data type name, and the backend will fill them in for you.
So, if you change the data type to
"dataType": {"name": "com.google.heart_minutes"}
It should work.
Then, you need to use the data source ID returned from that request for the data points.
Awesome, so after some support in the comments I have some working code to add a new session with data from a previously defined data source using 3 API calls. The first call is to create a data source and only needs to be run once. The second and third then add a data point to a data set and creates a new session for the workout respectively. Here's the final working code:
Data Source:
/*
gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000020",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
*/
Data and Data Set:
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:108881196053:op:6:1000020",
"userId": "me",
"datasetId": z,
"resource": {
"minStartTimeNs": workoutStartTime * 1000000,
"maxEndTimeNs": workoutEndTime * 1000000,
"dataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"point": [
{
"originDataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"value": [
{
"fpVal": 8
}
],
"dataTypeName": "com.google.heart_minutes",
"endTimeNanos": workoutEndTime * 1000000,
"startTimeNanos": workoutStartTime * 1000000,
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
Session:
gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": id,
"id": id,
"name": "Morning Workout",
"description": "A very intense workout",
"startTimeMillis": workoutStartTime,
"endTimeMillis": workoutEndTime,
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": workoutEndTime - workoutStartTime
}).then((res) => {console.log(res)});
console.log('res')

How can I import a json file in a JavaScript file?

I have two files data.json and index.js.
data.json looks like this:
{
"stacy": {
"age": 24,
"name": "Stacy",
"properties": [ "crazy", "funny", "straight" ]
},
"john": {
"age": 41,
"name": "John",
"properties": [ "experienced", "direct", "straight" ]
},
}
How can I import data.json into index.js?
I thought about something like this: import * as persons from data.json;
You will find all of your JSON data in the data variable.
By using fetch API you can load JSON data. Code below:
fetch('data.json')
.then(res => {
return res.json();
})
.then(data => {
console.log(data);
})
.catch(err => console(err));
try to write the exact file location.

Alexa ask-cli how to add a custom https server

I'm not able deploy alexa skill using alexa-cli tool (https://www.npmjs.com/package/ask-cli) when I try to deploy my skill with a https server
As an error I get:
◞ Creating new skill...Call create-skill error.
Error code: 400
{
"message": "Skill manifest is not valid.",
"violations": [
{
"message": "No default regionalized endpoint is defined."
}
]
}
Im using an example skill.json from:
https://github.com/alexa/skill-sample-nodejs-hello-world/blob/master/skill.json
A problem is how to add custom uri endpoint. I dont want to host my skill in AWS lambda function.
I tried to follow documentation:
https://developer.amazon.com/de/docs/smapi/ask-cli-command-reference.html
but I dont know what Im doing wrong...
Could sombody please take a look at my json and alexa-cli documentation? Why Im getting a such weird message?
"No default regionalized endpoint is defined."
?
{
"manifest": {
"publishingInformation": {
"locales": {
"en-US": {
"summary": "Sample Short Description",
"examplePhrases": [
"Alexa open hello world",
"Alexa tell hello world my name is bill",
"Alexa tell hello world I want to play"
],
"name": "trivia",
"description": "Sample Full Description"
}
},
"isAvailableWorldwide": true,
"testingInstructions": "Sample Testing Instructions.",
"category": "KNOWLEDGE_AND_TRIVIA",
"distributionCountries": []
},
"apis": {
"custom": {
"endpoint": {
"sourceDir": "./lambda/custom",
"uri": "https://customapi.sampleskill.com",
" sslCertificateType": "Wildcard"
},
"regions": {
"EU": {
"endpoint": {
"uri": "https://customapi.sampleskill.com",
"sslCertificateType": "Trusted"
}
}
}
}
},
"manifestVersion": "1.0"
}
}
Ok for those who faced that problem in the future ;) Important is that in your skill root directory you have that file:
.ask/config
It should look like:
{
"deploy_settings": {
"default": {
"skill_id": "put here your skill id or leave it blank",
"was_cloned": false,
"merge": {
"manifest": {
"apis": {
"custom": {
"endpoint": {
"uri": "https://yourhttps.de",
"sslCertificateType": "Wildcard"
}
}
}
}
}
}
}
}
after that you can use ask-cli with the https server as an endpoint :)
Try this:
"apis": {
"custom": {
"endpoint": {
"uri": "https://customapi.sampleskill.com",
"sslCertificateType": "Wildcard"
},
"regions": {
"EU": {
"endpoint": {
"uri": "https://customapi.sampleskill.com",
"sslCertificateType": "Trusted"
}
}
}
}
}
In the default config you had set sourceDir which doesn't make much sense for endpoints outside AWS Lambda. Second your config contained whitespace around sslCertificateType, which also might cause the problem.

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
}

Categories

Resources