Hi there I'm using a api which returns as follows
{"secret-finance":{"usd":0.04883396}}
Problem is I'm using vue and retrieving data like this
async getCurrentSefiPrice() {
await axios
.get(
"https://api.coingecko.com/api/v3/simple/price?ids=secret-finance&vs_currencies=usd"
)
.then(
(response) =>
(this.sefi_token_current_price = response.secret-finance.usd)
// console.log(response)
);
console.log(this.sefi_token_current_price);
}
But when I use secret-finance to get usd value I get an error.
Thanks in advance.
#haseebsaeed
You'll need to reference it as
response["secret-finance"].usd
You need to use key notation rather then dot notion when a key has a hyphen in it. Any key that contains characters that are not allowed in JavaScript variables you'll need to reference them as above.
A further example,
If the secret-finance object has a property key of us-dollars rather than the current one of usd, you would then access it by doing,
response["secret-finance"]["us-dollars"]
Related
I was using OMDBapi to get the details of different movies. I successfully fetched the result and it returns a json object like this;
{"Title":"WWA: The Inception","Year":"2001","Rated":"N/A","Released":"26 Oct 2001","Runtime":"N/A","Genre":"Action, Sport","Director":"N/A","Writer":"Jeremy Borash","Actors":"Bret Hart, Jeff Jarrett, Brian James, David Heath","Plot":"N/A","Language":"English","Country":"Australia","Awards":"N/A","Poster":"https://m.media-amazon.com/images/M/MV5BNTEyNGJjMTMtZjZhZC00ODFkLWIyYzktN2JjMTcwMmY5MDJlXkEyXkFqcGdeQXVyNDkwMzY5NjQ#._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"6.0/10"}],"Metascore":"N/A","imdbRating":"6.0","imdbVotes":"22","imdbID":"tt0311992","Type":"movie","DVD":"N/A","BoxOffice":"N/A","Production":"N/A","Website":"N/A","Response":"True"}
Note that we get this type of object from the api if we want to get a particular movie details and that is what i was doing. Now to show the different details to a user, i started parsing this JSON object which works fine but when i try to get the value of the Value key present inside the Ratings key, it returns undefined.
I am working with react-native. After getting the data, i stored it inside the state, named it as details. Then to get it;
this.state.details.Title //if i wanted to get the Title and it works fine.
Then for Value inside Ratings;
this.state.details.Ratings[0].Value
But it returns undefined.
Also note that this works fine in pure Javascript as i parsed the dict in the browser console in the same way and it returned the correct value.
Here is more code;
componentDidMount() {
this.fetchData();
}
fetchData = async () => {
const response = await fetch(`http://www.omdbapi.com/?i=${this.props.navigation.getParam('i')}&apikey=******`) // where this.props.navigation.getParam('i') is the omdbid of the movie
const result = await response.json()
this.setState({details: result})
}
Here is error log;
undefined is not an object (evaluating 'this.state.details.Ratings[0]')
You're most likely trying to access state object before fetch has done it's job .... it's an async op ... so you should make sure your data is ready before rendering...
if (this.state.details) {
// start rendering...
}
More Explanation
your setState function should be executed right after fetch has finished its job, and since it's an async operation, it's going to take some time ...During that time, render function is executed with no state.details --> causing your issue ...
That's why you should check for state before rendering ... besides, the optional chaining trick Silversky Technology mentioned in his answer
If the value property you are accessing from the object might be not available for all the movies in the data you are getting from API response so it might cause you to error when accessing key from undefined objects.
To overcome the issue there is a way, you can try a fix as below:
this.state.details.Ratings[0]?.Value
The ? symbol lets the javascript not give an error when the value key not available in the object. it will make the accessing of property optional.
When storing objects in states it often causes problems as you are doing in line
this.setState({details: result})
Save result after strigifying it like
JSON.stringify(result)
this.setState({details: result})
Then when fetching form state, parse it back to object by
var result = JSON.parse(this.state.details)
Then you should be able to access it
You can access Ratings[0].Value by
this.state.details.Ratings && this.state.details.Ratings[0].Value
like,
<Text> {this.state.details.Ratings && this.state.details.Ratings[0].Value} </Text>
I'm working with a non-profit cat shelter trying to update their website. They want to have a page that connects to their shelter manager software to display the available cats for adoption. Luckily, their shelter manager offers API calls to get the information I need from it.
They use Wix as their platform and are pretty set on keeping it as most of their volunteers know how to make easy adjustments to other pages. I researched and found Wix offers the ability to connect to the API using their fetch method.
Basically, I am trying to get a dynamic page to display a repeater that is populated from their json API Get method.
Currently, for the backend I have (URL to API removed for security):
import {fetch} from 'wix-fetch';
export function getdata(){
return fetch('URL to API Service', {method: 'get'})
.then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
} );
}
On the page, this is where I think I am getting stuck:
import {getdata} from 'backend/fetchCats';
getdata()
.then(json => {
console.log(json);
var catData = json;
// static repeater data
$w.onReady(function () {
// handle creation of new repeated items
$w("#repeater1").onItemReady( ($item, itemData, index) => {
$item("#text23").text = itemData.ANIMALNAME;
} );
// set the repeater data, triggering the creation of new items
$w("#repeater1").data = catData;
} );
});
The above is giving me the error: Wix code SDK error: Each item in the items array must have a member named _id which contains a unique value identifying the item.
I know the JSON call has an ID field in it, but I am guessing Wix is expecting an _id field.
Am I just doing this wrong? Or am I missing something simple? I've spent a couple nights searching but can't really find a full example online that uses Wix's fetch method to get data via my HTTPS Get.
Thanks for any help!
You are doing fine.
You are getting the error from the line $w("#repeater1").data = catData;
which is the line used to set the items into the repeater. A repeater expects to have a _id member for each of the items, and your data quite probably does not have such an attribute.
I assume the API you are using, when returning an array, each item has some identifying attribute? if so, you can just do a simple transform like -
let catDataWithId = catData.map(item => {
item._id = item.<whatever id attribute>;
return item;
});
$w("#repeater1").data = catData;
So I am still kind of a novice at Angular 2. My API call returns an object with several arrays and objects within it.
This is the JSON object I receive when i make the get request
{"report":[{"customer_name":"kaminto" ,
"customer_address":"Second","tel_no":"Second","id":"15","order_no":"RC13",
"total_amount":"28000","amount_paid":"30000","balance":"-2000",
"sale_date":"2017-08-15" ,"customer_id":"21"},"}], "message":"success" ,
"totalSales":[{"amount_paid":"1174300"}]}
I want to output the customer_name and address but they are within the Report array.
Using observables, How can I save this information into objects that i can bind to the html.
Please help.
[SOLVED]
I know this is embarrassing, but i solved it. I just had to add the string type and array brackets to the interface report variable.
export interface ISalesReport{
report:string[];
message:string;
totalSales:string[];
}
I don't know exactly why, but after i did this, it worked.
You get that object from Observable? Yes, it is not necessary if you only need value of two properties. Something like this should help:
customer_name;
customer_address;
yourObservable.map(allReports => allReports.map(report => report
.map(val => { this.customer_name = val.customer_name;
this.customer_address = val.customer_address } ));
Suppose you called your service in your component that returns an observable of the GET call.
In your Service,
getCall() {
return this.http.get(...).map((res) => res.json());
}
In your Component, (say you assign to a property),
responseObj: Observable<any>;
// say you receive values in ngOnInit(),
ngOnInit() {
this.responseObj = this.service.getCall();
}
In your html, use the async pipe for eternally binding it to the observable,
<div [innerHTML]="(responseObj | async)?.report[0].customer_name"></div>
<div [innerHTML]="(responseObj | async)?.report[0].customer_address"></div>
Hope it helps.
I've been looking for info about this for hours without any result. I am rendering a page using React, and I would like it to display a list of Django models. I am trying to use ajax to fetch the list of models but without any success.
I am not sure I understand the concept behind JSon, because when I use the following code in my view:
data = list(my_query_set.values_list('categories', 'content'))
return JsonResponse(json.dumps(data, cls=DjangoJSONEncoder), safe=False)
It seems to only return a string that I cannot map (React says that map is not a function when I call it on the returned object). I thought map was meant to go through a JSon object and that json.dumps was suppose to create one...
Returned JSon "object" (which I believe to just be a string):
For the time being I have only one test model with no category and the content "At least one note "
[[null, "At least one note "]]
React code:
$.ajax({
type:"POST",
url: "",
data: data,
success: function (xhr, ajaxOptions, thrownError) {
var mapped = xhr.map(function(note){
return(
<p>
{note.categories}
{note.content}
</p>
)
})
_this.setState({notes: mapped})
},
error: function (xhr, ajaxOptions, thrownError) {
alert("failed");
}
});
Can someone please point me to the best way to send Models from Django to React, so I can use the data from this model in my front end?
I recommend using the Django REST Framework to connect Django to your React front-end. The usage pattern for DRF is:
Define serializers for your models. These define what fields are included in the JSONified objects you will send to the front-end. In your case you might specify the fields 'categories' and 'content.'
Create an API endpoint. This is the URL you will issue requests to from React to access objects/models.
From React, issue a GET request to retrieve a (possibly filtered) set of objects. You can also set up other endpoints to modify or create objects when receiving POST requests from your React front-end.
In the success function of your GET request, you will receive an Array of Objects with the fields you set in your serializer. In your example case, you would receive an Array of length 1 containing an object with fields 'categories' and 'content.' So xhr[0].content would have the value "At least one note ".
In your code, the call to json.dumps within the JsonResponse function is redundant. Check out the docs for an example of serializing a list using JsonResponse. If you are serializing the object manually (which I don't recommend), I'd use a dictionary rather than a list -- something like {'categories': <value>, 'content' : <value>}. DRF will serialize objects for you like this, so the fields are easier to access and interpret on the front-end.
I have developed a MediaWiki extension that gets a (JSON) string from an external service using cURL.
Now I'm looking for a way to retrieve just that string from the MediaWiki system. (This URL will be used for AJAX calls.)
First, I thought that MediaWiki API was the way to do that. However, I can't seem to be able to output just that string.
What would be the right way to achieve this?
UPDATE
Thank you, that did the trick. For your information, here's how far I got:
$this->getResult()->addValue(null, null, array( 'autocomplete' => array( 'server', 'servers' ) ) );
returns [{"autocomplete":["server","servers"]}] when appending format=json to the API URL. Instead of the above JSON string, the JavaScript client I'm working with needs {"autocomplete":["server","servers"]} in order to work correctly. In other words, I needed to get rid of [ and ].
Just out of curiosity, is a custom printer still the way to go?
In your API module, override getCustomPrinter():
public function getCustomPrinter() {
return new ApiFormatRaw(
$this->getMain(),
$this->getMain()->createPrinterByName( 'json' )
);
}
(the nested createPrinterByName() call is for fallback format in case of errors, you can change it to some other format)
Then, in your execute() method or wherever you need to return the value:
$this->getResult()->addValue( null, 'text', $data_you_want_to_return );
$this->getResult()->addValue( null, 'mime', 'application/json' );