Getting a value from JSON API - javascript

So as of now I have successfully pulled data from a 3rd party website's API, but I'm still struggling to pull the value out of it. The data is formed in the following way:
My code currently looks somewhat like this:
Request.get("url", (error, response, body) => {
if(error) {
return console.dir(error);
}
console.dir(JSON.parse(body));
var obj = JSON.parse(body);
var priice = obj.data.items_on_sale.price;
console.log(priice);
});
So I'd like to pull out the price value but I don't know how to do it correctly. If I remove the last 3 lines I get this: "data: { items_on_sale: [ [Object] ], items_not_on_sale: [] } }", and if I keep it as it is I still can't pull the price value successfully... Any advice?

var obj = JSON.parse(body);
var priice = obj.data.items_on_sale[0].price;
console.log(priice);
This is what you are looking for.

var obj = JSON.parse(body);
var priice = obj.data.items_on_sale[0].price;
console.log(priice);
Is the way to go :)

Related

How to loop through a JSON array using for each in Zoho CRM Deluge script

**im a bit confused on how to declare an array in a deluge script. I have seen the references online but somehow i may not be using this syntax right:
x = List();
**
and here is my foreach loop
request_body is receiving the JSON array from my server
I get an error Argument type mismatches for the integration function 'zoho.crm.createrecord' at index 2 Line Number: 15
this my code to send the JSON array to CRM
async function sendToCRM(pets) {
var jsonPets = JSON.stringify(pets)
superagent
.post(insertPet_URL)
.set("Content-Type", "application/json")
.send(jsonPets)
.end((e, r) => {
console.log(r.body)
})// sends a JSON post body
}
app.post("/pets", (req,res)=> {
var pets = req.body
var petsData = []
pets.forEach(function(pet){
var tmp = {}
tmp["Name"] = pet.Ngalan
tmp["Pet_Owner"] = pet.Tagiya
tmp["Contact_Number"] = pet.Numero
tmp["Birthdate"] = pet.Kaadlawan
tmp["Breed"] = pet.Rasa
petsData.push(tmp)
})
console.log(petsData)
sendToCRM(petsData)
res.send(req.body)
res.status(200)
})
there has been no problem on the server side and im able to receive this JSON array from Postman which is the one im going to send to CRM deluge. Here is my JSON array:
[{"Ngalan":"Hachi","Tagiya":"Rex","Numero":"09778135353","Kaadlawan":"2020-12-12","Rasa":"Akita Inu"},{"Ngalan":"qwe","Tagiya":"Rex","Numero":"09778135353","Kaadlawan":"2020-12-12","Rasa":"Akita Inu"}]
Any help would be much appreciated. Thanks!
Make the request_body.tojsonlist(). then it work
First extract the keys from your response object, then iterate through your list and get the values
keys = request_body.keys();
for each key in keys
{
value = request_body.get(key)
}

How to pass external rest api data to a model as an Array of records?

I am trying to consume a .net core 2.2 web api i created and display the json data, keys AND VALUES, in a Google App Maker App. My js is very very weak (caz ive been trying to re-purpose the main example in googles docs for 7 days now with no real progress).
I have fought though many many issues to get to a final ERROR ( i hope).
When i commit some of the REST API data to the datastore. its ask for:
an array ( in js i guess arrays are objects...who knew)
a Key ( no idea how to make a key with out returning one FULL ITEM from the js object array i created for my data)
and for some form of mapping for the object ( i think i have overcome this requirement..not sure. this most likely will comeback after i fix the error bellow)
ERROR:
The function queryRecords must return an array of records, but the
array contained an element that was not a record. Error: The
function queryRecords must return an array of records, but the
array contained an element that was not a record.
Sun Sep 22 15:42:46 GMT-700 2019
Executing query for datasource Weather: (Error) : The function
queryRecords must return an array of records, but the array
contained an element that was not a record.
at loadWeatherDataSource (CallWeatherService:6:27)
at Weather.LocationTextBox.onValueChange:1:1
at Weather.LocationTextBox.onAttach:1:14
Sun Sep 22 15:42:46 GMT-700 2019
Executing query for datasource Weather failed.
Server side code
function clearEmailForm(){
var url= 'https://xxx.azurewebsites.net/api/xxxxxx/3';
var response1 = UrlFetchApp.fetch(url);
var api1= response1;
return JSON.parse(api1);
}
function cal() {
var coordinates = clearEmailForm();
return {
forecast: coordinates.Scene,
citystate: coordinates.imageurl
};
}
function calculateWeatherModel_() {
var response;
try {
response = cal();
} catch (error) {
throw new Error('Error Unable to locate provided city: \"' + response + '\".');
}
if (response === null) {
throw new Error('null Unable to locate provided city: \"' + response + '\".');
}
var forecastPeriods = response.forecast;
var citystate = response.citystate;
var arr = [];
var record = app.models.Weather.newRecord();
arr.push(record.forcast = forecastPeriods );
var record = app.models.Weather.newRecord();
arr.push(record.citystate = citystate);
return arr;
}
Client side code
function loadWeatherDataSource() {
app.datasources.Weather.load({
failure: function (error) {
displayTimedSnackBar(error.toString());
}
});
}
Client side code
return calculateWeatherModel_();
Thanks ahead of time for any and all detailed help here..I am at a complete loss and will have to delay a critical project.
I will now study and start to mastering JS as i see a clear need! I have my books and online course ready to go. if i can get some detailed help on this issue it will give my project some new life now instead of a long time from now. thank you all!
I beleive that your problem is here:
var arr = [];
var record = app.models.Weather.newRecord();
arr.push(record.forcast = forecastPeriods );
var record = app.models.Weather.newRecord();
arr.push(record.citystate = citystate);
return arr;
That is a wrong way of doing it. It should be like this:
var arr = [];
var record = app.models.Weather.newRecord();
record.forcast = forecastPeriods;
record.citystate = citystate;
arr.push(record);
return arr;
Obviously, in order for that to work, your calculated model should have a forcast field and a citystate field.
Reference: https://developers.google.com/appmaker/models/calculated#query_script_example

javascript How to check the same data is available for the second time

I have a tricky requirement which im not able to fix.
I have a button and if i click on that button, Im getting below data from a REST web service ..
{
"results": [{
"Reqdate": "\/Date(1520899200000)\/",
"Tooltip": "13.03.2018 Blood Donation Approved ",
"Legendid": "GROUP_LEVEL1"
},{
"Reqdate": "\/Date(1523836800000)\/",
"Tooltip": "16.04.2018 Privilege Leave Sent ",
"Legendid": "BADVALUE_LIGHT",
},{
"Reqdate": "\/Date(1524528000000)\/",
"Tooltip": "24.04.2018 Privilege Leave Sent ",
"Legendid": "BADVALUE_LIGHT",
}]
}
If im getting the above data for the first time. Im going to display one section. Now again if i click on the same button, If i get the same data in the service then i have to hide the section. But im not able to check the same data for the second time.
Im trying to fix this issue by storing the data in a variable like below..
var firstTimeResults = data.results;
Now im not able to check if the same data is coming for the second time. Actually im not able to produce the sample code too. Im sorry for that
Can someone please help me to fix this issue.
I am not fully understand your problem but I think you can store your data as JSON and check if the same data is return from the second time onwards?
Code example
// Variable declaration
var firstTimeResults = null;
// When data return
var dataJson = JSON.stringify(data.results);
if (firstTimeResults === null) {
firstTimeResults = dataJson;
}
else {
// check to see if the data is the same as the firstTimeResults
var isSame = firstTimeResults === dataJson;
if (isSame) {
// Same
} else {
// Not the same
}
}
You can simply try with Lodash library.
It makes JavaScript easier to work with arrays, numbers, objects, strings, etc.
https://lodash.com/
var firstResult = null;
var secondResult;
var showSection;
function getData() {
// here goes your API request to get the data
};
function onButtonClick() {
this.getData().then(function(value) {
if !(firstResult) {
firstResult = value;
showSection = true;
return;
}
secondResult = value;
if (_.isEqual(firstResult, secondResult)) {
showSection = false;
}
})
};
Hope this will be helpful to you!

How to use multiple callbacks when looping data

I'm trying to get HTML form data, loop it through, change it a bit and insert it to database. I have tried like below app.js.
How can I make callbacks so that formdata what I have modified is available for .create function?
I have searched from everywhere and I always end up in dead end and undefined variable somehow.
app.js:
//Find the day where to save
Day.findById(req.params.id, function(err, day) {
if (err) {
console.log(err);
res.redirect("/diary");
} else {
// Search function to find data with _id
function ingredientIdQuery(reqBodyId) {
var ingQuery = Ingredient.find({_id:reqBodyId});
return dbQuery;
}
// This loops through HTML formdata and formats it for mongoose model
for (var i = 0; i < req.body.amount.length; i++) {
if (req.body.amount[i] !== "") {
var amount = Number(req.body.amount[i]);
var singleMealTempObj = {};
singleMealTempObj.amount = amount;
var _id = req.body.id[i];
var query = ingredientIdQuery(_id);
// Executing the query for the data I need with id
query.exec(function(err, ingr){
if(err) {
return console.log(err);
} else {
singleMealTempObj.ingredient = ingr[0];
singleMealTempArr.push(singleMealTempObj);
}
});
}
}
}
// This inserts data into day
Meal.create(singleMealTempArr, function(err, singleMealObject) {
if (err) {
console.log(err);
} else {
day.meals.push(singleMealObject);
day.save();
res.redirect("/day/" + day._id + "/dayshow");
}
});
});
});
Edit:
Thanks for reply and notices! While I was trying to do everything to get this work I missed those few things like declaring variables. Sorry for that. I threw the towel in to the cage at this point.
flow goes like this:
User sends HTML form data to app.js which is inside object of two arrays (id[] and amount[]). Amount array needs to be looped through if it has value other than 0. Same index id array value is used to fetch data from database. This data what is found from database with id from id[] is used with same index amount[] and it should be saved to mongo.
I can get the values from HTML form ok. but I have tried to make a search in Mongo in a for loop (query.exec in the code) I get the data ok. When I log the data outside the database query, variable is undefined.
I hope this clarifys a bit what I'm trying to achieve.
I'll continue this later... :)
I guess issue originates because of this function.
function ingredientIdQuery(reqBodyId) {
var ingQuery = Ingredient.find({_id:reqBodyId});
return dbQuery;
}
Is find function asynchronous or synchronous?
Also you are returning dbQuery but dbQuery does not seem to be changed inside the function.
Couple I noticed that may fix this:
You never define singleMealTempArr, so when you try to push data to it, you are gonna run into problems.
Your ingredientIdQuery function returns dbquery - which also isn't defined. You actually call it ingQuery. Even so...are you positive that this will return the data that you want?
// lets loop through all the form fields in req.body.amount
for (var i = 0; i < req.body.amount.length; i++) {
// keep going unless the form field is empty
if (req.body.amount[i] !== "") {
// assign all the form fields to the following vars
var amount = Number(req.body.amount[i]);
var singleMealTempObj = {};
singleMealTempObj.amount = amount;
var _id = req.body.id[i];
var query = ingredientIdQuery(_id);
// we are executing the ingredientIdQuery(_id), better
// double-check that this query returns the result we are
// looking for!
query.exec(function(err, ingr){
if(err) {
return console.log(err);
} else {
singleMealTempObj.ingredient = ingr[0];
// now that we've gone through and mapped all the form
// data we can assign it to the singleMealTempArr
// WOOPS! Looks like we forgot to assign it!
singleMealTempArr.push(singleMealTempObj);
}
});
}
}
}

Using nodejs to parse JSON

So, I'm using nodejs to parse json, and I'm wanting to get an object that's an array and use the values in a for each loop.
JSON I'm getting: http://tmi.twitch.tv/group/user/loneztar/chatters
var cronUsers = client.utils.cronjobs('1 * * * * *', function() {
console.log('API Test');
console.log('Response from Twitch Chat:');
request('http://tmi.twitch.tv/group/user/loneztar/chatters', function (error, response, body) {
if (!error && response.statusCode == 200) {
data = JSON.parse(body);
console.log(data.chatters.viewers);
//for each string in the viewers
}
})
});
Above is the code I'm using to retrieve the data. And when I log to the console I get the following (at time of asking):
[ 'duckziller72',
'adanaran',
'nyckeln',
'diabolicalsheep69',
'audery101',
'gone_nutty',
'k4unl',
'eidokan',
'mattesolo',
'siland',
'nullvoid8',
'troy00114',
'sixdev',
'jake_evans',
'doctoranguus',
'juicegraip',
'k4rush' ]
Now I want to use each of them strings in a for each loop. I've tried using the data var I'm using but I can't get anything working. Would appreciate some help! Feel free to ask for other stuff, I'll happily edit.
There are a few different ways to do this.
Using a loop counter:
var viewers = data.chatters.viewers;
var numViewers = viewers.length;
for (var i = 0; i < numViewers; i++) {
var viewer = viewers[i];
console.log(viewer);
}
Using 'for .. in':
var viewers = data.chatters.viewers;
for (var i in viewers) {
var viewer = viewers[i];
console.log(viewer);
}
You may have been trying to use this, but the loop variable contains the indices of the array, not the values.
Using Array.prototype.forEach():
data.chatters.viewers.forEach(function(viewer) {
console.log(viewer);
});
Note that none of this is specific to Node.js or JSON responses.

Categories

Resources