I'm trying to call the API but it doesn't return me anything.
I'm calling it like: res.on('data', d => { const RetrieveFromApi = JSON.parse(d).FLUX.quote.USD.price;.
The API is successfully called since I can see it in the API history, and data is defined as d.
Can you help me please?
from your screen provided in comment, you passed one property you don't access to it which is data
So just add property data before FLUX
JSON.parse(d).FLUX.quote.USD.price;
^data.FLUX.quote.USD.price;
From the image of the log the object seems incomplete at the end, did you try to use JSON.stringify(d) to see if there are any errors on the json object? or copy the response on https://jsonlint.com to check?
Because the error message points that the parse doesn't find a valid json object, maybe that is the whole point.
And the other tip is to try to store the value of JSON.parse in an variable before trying to access his values.
Related
i want to retrieve the location from the fetched API of open cage geocoding which has the following structure
this picture contains the structure of data strogae
pls help me out
When using fetch you can usually accomplish it like this:
fetch("https://api.opencagedata.com/geocode/v1/json?q=51+16&key=YOUR_KEY")
.then( response => response.json())
.then( data => console.log(data.results))
The first line returns a response Promise. The second line contains instructions on how to parse the response body. In this case, you want to parse JSON, hence, you call res.json().
More on the latter part can be found here.
I'm incredibly stuck on trying to format receive a JSON response, and format it. Order of operations:
Query a REST API endpoint (https://endpoint.com/api/v1/employee?id={username})
Receive JSON response: {"employee":{"full name":"Example Name","function":"Role","office":"Office Location",team":"Team 1|Team 2|Team 3|"}}
In my base.js file within my django app, I am hoping to extract the team strings and pass them into another URL. What way can I do this? When I $.getJSON from the endpoint I receive responseJSON, responseText, etc. but I'm unable to pull them out/use them in any way.
In order to fetch and parse json I would suggest you to use the following fetch structure:
fetch('https://endpoint.com/api/v1/employee?id=username')
.then(response => response.json())
.then(data => {
let teams = data.team.split('|');
// Do something with team names
});
Let's break down what this does per line:
First we use fetch to request data from the defined url
Then we convert the response to a json object
Finally we retrieve the string with team values using the data.teams statement, after which we immediately convert the list of team names to an array by using split and the defined delimiter |.
After this you should be able to do whatever you'd like with the team names. You could use them to make another API call as well. If you're interested, be sure to checkout the fetch documentation, as well as the split documentation if you are not yet familiar with that function.
The solution above assumes that the response will be a 200, for error handling you should check out the fetch documentation above.
I am trying to learn working with API calls and responses and I needed a basic value that comes from api response but I wasn't able to get it work. So here is my problem;
(function worker() {
$.get('URL', function(data) {
$('#numbers').html(data); });
})();
I use this code and this works perfectly fine, and writes the API response to my HTML page. Also the API calls return the value in this format;
{
"success":"true",
"field1": {"number1":"number1_val","number2":"number2_val"},
"field2": {"number11":"number11_val","number22":"number22_val"}
}
Now, I tried to write the values from API response and I was successfull for writing the "success" value like this;
$('#success_val').html(data.success);
It printed true value to my HTML website in given #success_val field. However, when I tried to write the field1, or the first value of field1, I wasn't successful. I tried
$('#numbers').html(data.field1); => No success, empty page
$('nu#mbers').html(data.field1[0]); => No success, empty page
So, at this point, what I need to store & use is the "number11" value from field 2. I have read and searched for over an hour and found out that this api return is not a valid "array" return, instead it is called "field" (I might be wrong), but I couldn't find any info about how can I get the "number11" data from this api response.
$('#numbers').html(data.field1); => No success, empty page
Does data.field1 exist for sure? or spelling check.
you can get keys by Object.keys(data).
If exist data, it return ["success", "filed2", "field2"].
In the same way, you already know key, like number11,
data.field2.number11 or data["field2"]["number11"] return value.
If you don't know key, data["filed2"][Object.keys(data)[0]] return value
Thanks to https://stackoverflow.com/users/10366589/sh-k I have solved the problem in given way;
As I wasn't able to print output from field2 to HTML, I have checked keys at field2 with this code;
alert(Object.keys(data.field2));
and it returned
number11,number22
since I only needed number11 from that API response, I did the following;
var.storednumber = Object.keys(data.field2);
var.storednumber = storednumber[0];
$('#numbers').html(storednumber);
and I was able to get the number I wanted printed on the screen without any problem :)
There could be a better solution or fix for the issue I am having, but for now, this has solved. I guess the problem lies on the API response type as it doesn't return an array formatted data.
Problem
In a social media app I am making with react native and firebase, I am trying to grab the number of comments a post has using the snapshot function of a variable I have saved on my servers, then I am going to add one to this variable when a user adds a new comment. My code to do so is right here:
firebase.database().ref('posts').child(this.state.passKey).update({
comments: firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
})
When I actually run this code, I get an error saying:
Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".","#","$","[", or "["
At first I thought this might be that the "this.state.passKey" wasn't actually passing the key, but putting in a key I copied from the server didn't fix the problem.
My Server
-
To get the comments of particular post you should do like this
let postId='someId'
postRef=`/posts/${postId}`
firebase.database().ref(postRef).once("value", dataSnapshot => {
comment=dataSnapshot.val().comments
});
It looks like you're expecting this bit of code to query the database:
firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
Unfortunately, it doesn't work that way. There's no snapshot property on a database Reference object returned by child() or ref().
Instead, you'll need to query the database at that reference, then when you're called back with its value, you can apply it elsewhere.
var ref = firebase.database().ref('posts/'+this.state.passKey+'/comments')
ref.once('value', function(snapshot) {
// use the snapshot here
})
The following code from Bacon.js will push the data object returned from the AJAX request into the console.
Bacon.fromPromise($.ajax({ url : requestUrlString })).log()
What is not clear, is how to assign the returned data object to a variable, or to do anything with the data object when a response is returned.
As per documentation (https://github.com/baconjs/bacon.js/#bacon-frompromise) the fromPromise method returns an EventStream object, whose onValue method you can use to attach a callback for handling the data. But that you can of course do without Bacon.js too. The point of the library is that you can gather, combine, filter and transform data from various sources and separate side-effects from data handling logic.