Inserting the JSON file data into a database

My website gets flights information from an API into a json format.
I would like to insert the json data into my database I connected.
is it possible?
If it is, how do I do it?
e.g the Javascript code -

fetch(’ https://api.skypicker.com/flights?v=3&sort=price&locale=en&partner=picky&flyFrom=IST&to=AYT&dateFrom=03/02/2018&dateTo=03/02/2018&typeFlight=oneway&adults=1&curr=EUR ', {method: ‘get’})
.then( (httpResponse) => {
if (httpResponse.ok)
{
return httpResponse.json();
}
else
{
return Promise.reject(“Fetch did not succeed”);
}
} )

Eilon,

Have you tried using this api? https://www.wix.com/code/reference/wix-data.html#insert

Shlomi

Thanks Shlomi this API seems to be really helpful.
The only thing that I still don’t understand is how can I get the JSON information into the data… how do I parse it?
Is there an example using JSON and DB?

Can you please share what exactly you are trying to do? An example would really help me better understand. Usually what a developer would try to do is receive data from an external api as json, treat it as a JavaScript object and then extract data from it to be mapped into numerous different explicit columns

I was trying to get the JSON data that contains flights data ( I got it using a 3rd service API from a flights provider) . Now when I have the JSON file I am trying to show the data to the user…
The way I was thinking of doing it is to import it into a database first… then it would be easier to use the values of the database for the user… like Flight from, to, time of the flight etc…

Indeed you will also want to let the user search and filter flights matching his criteria, so using a collection to model the flights is the right way to go!
Lets say your response json object is ‘res’, then res.from, res.to (depends on the actual data you get from the api) should work. Just map it to the structure of your predefined collection and use the insert api to save it in your db. JSON actually stands for Java Script Object Notation so it is that easy :wink:

Search online for a ‘json online viewer’, run the api call you pasted above in a regular web browser and paste the response text in an online viewer. It will show you the exact structure. For example i see that you need to : ‘res.data’ which is an array of results. So res.data[0] is your first result. Hope it makes sense

Can you please share the url of the site you are trying to build?

www.flilu.com

I’m trying to get the results of the return from the search_buttonclick into search_results (JSON file format)
And then use the results and insert it into my Flights collection.
Then in my flights page (a page search button is linked to) I will show the collection data… which is the flights results (from, to, hours etc…)

I added a foreach loop so every item in the array will get into the datacolletion… but still it doesn’t put it inside the datacollection…

export function searchButton_click(event, $w) {

fetch(‘https://api.skypicker.com/flights?v=3&sort=price&locale=en&partner=picky&flyFrom=IST&to=AYT&dateFrom=03/02/2018&dateTo=03/02/2018&typeFlight=oneway&adults=1&curr=EUR’, {method: ‘get’})
.then( (httpResponse) => {
if (httpResponse.ok)
{
return httpResponse.json();
}
else
{
return Promise.reject(“Fetch did not succeed”);
}
} );

}

var search_results = searchButton_click();
search_results.forEach( (item) => {
wixData.insert(“Flights”, item)
.then( (results) => {
let item = results; //see item below
} )
.catch( (err) => {
let errorMsg = err;
} );
});

Eilon,

thanks for sharing the code sample. there are a few issues we might want to have a better look into:

  1. the results processing code should be within the following block:
    if (httpResponse.ok){/* process your code here */}
    note that the function receives 2 parameters searchButton_click(event, $w) which you are not even passing with your own function call. you do not have them in your context, so the function can not work in this way at all.

  2. the data you get back is not an array or results but it look like this below. please see my advice above about using a json viewer. the results are within the ‘data’ nested within the json


3. you need to create a matching collection schema with all the data you want to store and map the results to the db item, not directly like that - wixData.insert(“Flights”, item) but take the data inspect each result and take only what you want to map directly to a column within your collection. their api may change and will easily break your code - see below how each of the items look like :

  1. i also recommend you move this code to the backend rather than running loop of inserts from the user browser all the way to wix servers. it is best done within wix servers to minimize the latency

5: i am not really sure you want to store the result in a db collection from the first place, as it is specific per user, per specific search parameters (given destination etc) plus, maybe those flights results will not be correct in a few minutes/hours.

good luck!
Shlomi

Wow shlomi. Thats amazing information.
Before I start fixing my code, I wanted to consult with you on Number 5.
You are aaying maybe i should not store my data in a collection for the first place. If so, should I just show the data in right away? Like parse the Json to the flights page and ahow it to the user?
You think its better? If it is, I will not store it at all.

Hi Eilon,

You should only store the responses if you plan on using them in the future.
Due to the nature of these searches it is probably best not to store them and bring them into view as soon as they are ready for viewing.

Best regards,

Ok,
So now I’m not putting my data into the data collection and I just try to print it.
var search_results = httpResponse.json();
document.getElementById(“text14”).innerHTML = search_results.data[0];
so I got into my search results the json file…
Then… I’m trying to access the first element under data…and to write it into a “text14” label.

  1. I got an error that document not defined… why? it is a common java sciprt command…
  2. text14 is a label in another page… my search button clicked… get the information from the API and connects to another page where my label text14 is located… how can I move code between the pages?
  3. is search_results.data[0] is correct?

Hi,

The $w namespace allows you to interact with page components.
To change a text value, use:

$w("#textElement").text = "Text Value";

It is not possible to directly communicate between site pages since only one page is active at a time.
There are, however, a number of ways to share information between pages.
For example you could store an ID token in the user’s session storage (with wix-storage) and use it to fetch some information from a database once the visitor loaded the second page.

Yes, search_results.data[0] should give you the results.

Hi,
So I used your tip and store the user’s session in wix session.

So first I tried to took the “from” value from the json file.
The button links to another page so after you click search it needs to save the sesion of From into Form.

Main Page -
export function searchButton_click(event, $w) {

fetch(‘https://api.skypicker.com/flights?v=3&sort=price&locale=en&partner=picky&flyFrom=IST&to=AYT&dateFrom=03/02/2018&dateTo=03/02/2018&typeFlight=oneway&adults=1&curr=EUR’, {method: ‘get’})
.then( (httpResponse) => {
if (httpResponse.ok)
{

  var search_results_json = httpResponse.json(); 
  session.setItem("From", search_results_json.data[0].mapIdFrom); 

}
else
{
return Promise.reject(“Fetch did not succeed”);
}
} );

}

Then over here… I have label with “Form” text… I try to change it to the session label I got from the Menu page… But instead it makes the text blankk… like the value I get is blank or something…
Any Idea?

Flights page -

// For full API documentation, including code examples, visit Velo API Reference - Wix.com
import wixData from ‘wix-data’;
import {session} from ‘wix-storage’;

$w.onReady(function () {
let value = session.getItem(“From”)

$w("#fromText").text = value; 

});

Eilon,

you are trying to receive the data in the scope of - $w.onReady - which is done on a page load. it is done before any button was clicked. in addition you are also taking the value from the first result - data[0]

as the site you are trying to build has a few steps on top of calling skypicker i’d advise you to avoid using any type of storage/cache at the moment and just display the results to the user first. i think it will help you clear out lots of good stuff along the way

goodluck,
Shlomi

Hi Shlomi,

First, on the main page there is a search button that links to the flight page. So first, the button is clicked and the function inside the function runs and then it links to another page and runs the $w.onReady…
So it’s supposed to run on the flight page or am I wrong?

Second, data[0] is what I want, because data[0] is contains a dictionary with mapIdFrom key that it’s content is where you fly from.

Also, I couldn’t even display the content on the same page…
I feel stuck… Like I can’t pull any information from the JSON no matter what I do… it just doesn’t show me no where… Is there something I just don’t understand?

Use console.log to see what you get, use code to filter your results