I have Json data and want to read genre data specially name key using Native Base. Here is my Json, I got it from TMDB API
the genres key using nested array to store the data
"genres": [
{
"id": 878,
"name": "Science Fiction"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 28,
"name": "Action"
}
],
I am trying to load data from API like this
fetchDetails = () => {
fetch(
`https://api.themoviedb.org/3/movie/${movie_id}?api_key=<API KEY>`
)
.then((response) => response.json())
.then((json) =>
this.setState({
contentGenre: json.genres[0]
})
)
.catch((error) => console.error(error))
.finally(() =>
this.setState({
isCategoriesLoading: false,
})
);
};
And I'm trying to display the genre like this, but the data isn't showing
<Text>{contentGenre.name}</Text>
Thanks for your help!
Not really sure what the issue is. The following code works and prints Drama at the console. I used a fixed value (345) for the movie id. Perhaps you should remove your API key from the question.
fetch(
https://api.themoviedb.org/3/movie/345?api_key=9b68fedd9d8cacc97e967403feb9d5fc
)
.then((response) => response.json())
.then((json) =>(
console.log(json.genres[0].name)
)
)
.catch((error) => console.error(error))
.finally(() =>
console.log("Done")
);
Here is how to access the name of the first genre.
fetch(`https://api.themoviedb.org/3/movie/${movie_id}?api_key=...`)
.then((response) => response.json())
.then((json) => json["genres"][0].name)
.then(console.log)
Related
I'm fetching this JSON from an API:
{
"data": {
"email": "test#tre.com",
"inserted_at": "2021-03-30T15:37:06",
"links": [
{
"id": 1,
"title": "My link title",
"url": "http://google.com"
},
{
"id": 2,
"title": "My Youube title",
"url": "http://youtube.com"
}
]
}
}
I'm fetching it this way using Hooks:
export default function Notes() {
const [json, setJSON] = useState([]);
useEffect(() => {
fetch("http://localhost:4000/api/users/1", {
method: "GET"
})
.then((response) => response.json())
.then((json) => {
// console.log(data);
setJSON(json);
})
.catch((err) => {
console.error(err);
});
}, [setJSON]);
Then I try to show it like this:
return (
<>
<div className="content">
{JSON.stringify(json)}
<h1>{json.email}</h1>
</div>
</>
);
The line {JSON.stringify(json)} shows the JSON.
But the line <h1>{json.email}</h1> doesn't show anything.
I don't know why that happens and how can I access my variables.
Thanks . I appreciate any help
Is the data in the form of an array or an object?
You defined the initial state as and array ad hence you cannot do
// you can't do json.email if you expect the response as and array
const [json, setJSON] = useState([]);
change it to
const [json, setJSON] = useState({});
if it is an object. Then in the template do
{json.data && <h1>{json.data.email}</h1>}
<h1>{json.data && json.data.email}</h1>
instead of
<h1>{json.email}</h1>
I feed JSON to some webhook to trigger a notification (M$ Teams). This works well. However, I want to extend my Perl script: I need to add a new node to my "messagecard" construct on a certain condition.
E.g. I defined this:
my $payload={};
$payload = {
'#type' => 'MessageCard',
'#context' => 'http://schema.org/extensions',
themeColor => $event{COLOR},
text => $event{SERVICEOUTPUT},
sections => [{
facts => [{
name => 'Type',
value => "$event{NOTIFICATIONTYPE} $event{ADDITIONALINFO}"
},
]
}],
potentialAction => [{
'#type' => "OpenUri",
name => "View Monitoring",
targets => [{
os => "default",
uri => $naemon_url
}]
}]
};
$ua = LWP::UserAgent->new;
my $req = POST($opt_webhook
, 'Content-Type' => 'application/json; charset=UTF-8'
, 'Content' => encode_json($payload)
);
my $resp = $ua->request($req);
And if (conditon), I want to extend this as follows (order is important):
$payload = {
'#type' => 'MessageCard',
'#context' => 'http://schema.org/extensions',
themeColor => $event{COLOR},
text => $event{SERVICEOUTPUT},
sections => [{
facts => [{
name => 'Type',
value => "$event{NOTIFICATIONTYPE} $event{ADDITIONALINFO}"
},
]
}],
potentialAction => [{
'#type' => "OpenUri",
name => "View Monitoring",
targets => [{
os => "default",
uri => $naemon_url
}]
},
{
'#type' => "OpenUri",
name => "Notes (Logs, Docs,..)",
targets => [{
os => "default",
uri => $event{SERVICENOTESURL}
}]
}]
};
I am unsure how this can be achieved. Can anyone please provide wisdom how to tackle this?
You can push into the array reference that you've got inside your potentialAction key. In order to do that, you need to dereference it as an array.
my $payload = {
'#type' => 'MessageCard',
potentialAction => [{
name => "View Monitoring",
targets => [{
os => "default",
}]
}]
};
if ($maybe) {
push #{ $payload->{potentialAction} }, {
name => "Notes (Logs, Docs,..)",
targets => [{
os => "default",
}]
};
}
If your Perl version is 5.24 or newer you can also use postfix dereferencing, which some people find easier to read.
push $payload->{potentialAction}->#*, ...
See perlref and perlreftut for more information.
I'm working with a JSON rest API that has the following response:
// response
[
{
id: 1,
userId: 1,
start: "2018-01-01 10:15",
finish: "2018-01-01 12:20",
breakLength: 30
},
{
id: 2,
userId: 1,
start: "2018-01-02 10:15",
finish: "2018-01-02 18:20",
breakLength: 45
}
];
See below for code. Like my other functions, I am requesting a GET using fetch(). However, sometimes this function when called requests and responds with a 200, and sometimes it responds with a 400 bad request(Uncaught (in promise) SyntaxError: Unexpected token B in JSON at position 0) It seems very random when it happens. My server which the JSON Rest API is on is localhost:3000 and my application is on localhost:3001. I have used this same method for other JSON requests and they work perfectly. I am not sure why this one is having trouble? Thanks for your help!
Update: It seems as though the last Promise.all, setState is not being executed. The program is crashing on line .then(response => response.json()) in promise3.
Updated Code:
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
callbackSessionId = (sessionId) => {
let promise1 = this.fetchUserAttributes(sessionId)
.then(response => response.json())
.then(json => this.setState({
userAttributes: json
}));
Promise.all([promise1]).then(() => {
let promise2 = this.getOrganisations(sessionId)
.then(response => response.json())
.then(json => this.setState({
organisations: json
}));
let promise3 = this.getShifts(sessionId)
.then(response => response.json())
.then(json => this.setState({
shifts: json
}));
// this.setState({
// sessionId: sessionId
// });
Promise.all([promise2, promise3]).then(() => {
this.setState({
sessionId: sessionId
});
});
});
};
Your JSON is actually invalid. All keys need to be string literals, so your correct JSON would look like this:
[
{
"id": 1,
"userId": 1,
"start": "2018-01-01 10:15",
"finish": "2018-01-01 12:20",
"breakLength": 30
},
{
"id": 2,
"userId": 1,
"start": "2018-01-02 10:15",
"finish": "2018-01-02 18:20",
"breakLength": 45
}
]
There are a few issues in your code: you should always return your promises, headers property names should be quoted and React setState is an asynchronous method.
Please, try to update it like below to see if it works, I'll edit expanding on the details if it does.
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
fetchData = (sessionId) => {
let promise3 = this.getShifts(this.state.sessionId)
.then(response => response.json())
.then(json => this.setState({shifts: json}, this.forceUpdate));
};
I'm really sure about, that this question is answered multiple times in here. But I can't find them/don't knwo which terms to search for.
I've got a JSON-file looking like that:
{
"pages": [{
"displayname": "PageA",
"url": "http://google.de",
"icon": "iconZ"
},
{
"displayname": "PageB",
"url": "http://www.pageb.co.uk",
"icon": "iconY"
}
],
"icons": [{
"alias": "iconZ",
"filename": "iconZ.svg"
},
{
"alias": "iconY",
"filename": "iconY.svg"
}
]
}
Now I'm using the HttpClient (here called httpService) to get the data from the file.
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data as string[];
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
I want to use the content of pages in my ngFor in the Frontend and I want to get an array of the icon-content for use in the Backend. How can I select/split the data by using the properties.
Thanks for your help
Elias
Considering your pageconfig.json is used in both front and backend, and that you just need the "pages" attribute in your angular app, you may get it this way:
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data.pages;
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
You don't need to cast the data type.
You could also use the rxjs observable map chaining to parse your data and get only what interests you:
import { map } from 'rxjs/operators';
this.httpService.get('./assets/pageconfig.json')
.pipe(map(data => data.pages))
.subscribe(pages=> {
this.arrAdress = pages;
}.catch((err: HttpErrorResponse) => {
console.log(err.message);
});
I hope this is what you were looking for.
Need to remove string[], instead use Array of object or any.
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data;
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
sendData(icon){
const matched = this.arrAdress.icons.filter(iconObj => iconObj.alias === icon);
console.log(matched);
}
**Template:**
<div *ngFor="let adress of arrAdress?.pages;" (click)="sendData(adress.icon)">
<span>{{adress.displayname}}</span>
</div>
You have two solutions here to solve this issue
Suppose httpClient.Delete() option returns back you an observable object with employeeId as property in it.
Solution 1 (example)
Create an local variable and assign data to it using let statement (e.g. let response: any = data;).
delete(employee: any) {
this.employeeService.deleteEmployee(employee.id)
.subscribe(
data => {
let response: any = data;
// now you can use response.employeeId
},
(error) => {
console.log(error)
},
() => {
console.log("The operation has been completed")
}
);
}
Solution 2 (example)
Assign type any (e.g. (data : any) to received response
delete(employee: any) {
this.employeeService.deleteEmployee(employee.id)
.subscribe(
(data: any) => {
// now you can use data.employeeId
},
(error) => {
console.log(error)
},
() => {
console.log("The operation has been completed")
}
);
}
I want to use the Citybik.es API (http://api.citybik.es/) to show data on a Leaflet map.
At the moment, the code is only showing the last item from the bikeData.map(), inside the render function.
The console.log(data) is showing every iterated item from the bikeData.map(), but only displaying the last item.
I am looking for something like this.
What am I missing?
The response looks something like this:
{
"networks": [
{
"company": [
"Bike U Sp. z o.o."
],
"href": "/v2/networks/bbbike",
"id": "bbbike",
"location": {
"city": "Bielsko-Bia\u0142a",
"country": "PL",
"latitude": 49.8225,
"longitude": 19.044444
},
"name": "BBBike"
},
{
"company": [
"PBSC",
"Alta Bicycle Share, Inc"
],
"href": "/v2/networks/melbourne-bike-share",
"id": "melbourne-bike-share",
"location": {
"city": "Melbourne",
"country": "AU",
"latitude": -37.814107,
"longitude": 144.96328
},
"name": "Melbourne Bike Share"
}
}
Here's the JavaScript:
import React, { Component } from 'react';
import L from 'leaflet';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
// code for map marker icon
var myIcon = L.icon({
iconUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAFgUlEQVR4Aa1XA5BjWRTN2oW17d3YaZtr2962HUzbDNpjszW24mRt28p47v7zq/bXZtrp/lWnXr337j3nPCe85NcypgSFdugCpW5YoDAMRaIMqRi6aKq5E3YqDQO3qAwjVWrD8Ncq/RBpykd8oZUb/kaJutow8r1aP9II0WmLKLIsJy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88PBTzD/gpeREAMEbxnJcaJHNHrpzji0gQCS6hdkEeYt9DF/2qPcEC8RM28Hwmr3sdNyht00byAut2k3gufWNtgtOEOFGUwcXWNDbdNbpgBGxEvKkOQsxivJx33iow0Vw5S6SVTrpVq11ysA2Rp7gTfPfktc6zhtXBBC+adRLshf6sG2RfHPZ5EAc4sVZ83yCN00Fk/4kggu40ZTvIEm5g24qtU4KjBrx/BTTH8ifVASAG7gKrnWxJDcU7x8X6Ecczhm3o6YicvsLXWfh3Ch1W0k8x0nXF+0fFxgt4phz8QvypiwCCFKMqXCnqXExjq10beH+UUA7+nG6mdG/Pu0f3LgFcGrl2s0kNNjpmoJ9o4B29CMO8dMT4Q5ox8uitF6fqsrJOr8qnwNbRzv6hSnG5wP+64C7h9lp30hKNtKdWjtdkbuPA19nJ7Tz3zR/ibgARbhb4AlhavcBebmTHcFl2fvYEnW0ox9xMxKBS8btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII=',
iconSize: [25, 41],
iconAnchor: [12.5, 41],
popupAnchor: [0, -41]
});
class App extends Component {
state = {
location: {
lat: 51.505,
lng: -0.09,
},
bikeData: [],
zoom: 2,
}
//lifecycle method to get the bike information
componentDidMount() {
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks;
networkData.map((data) => {
console.log(data)
this.setState({
bikeData: [data]
});
})
})
}
render() {
const position = [this.state.location.lat, this.state.location.lng]
const bikeData = this.state.bikeData;
return (
<Map className="map" center={position} zoom={this.state.zoom}>
<TileLayer
attribution="© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{
bikeData && bikeData.map((data) => {
console.log(data)
return (
<Marker
icon={myIcon}
key={data.id}
position={[data.location.latitude, data.location.longitude]}>
<Popup>
Name: {data.name} <br />
Station Details: {[data.location.city, data.location.country]}
</Popup>
</Marker>
)
})
}
</Map>
)
}
}
ReactDOM.render(<App/>,
document.getElementById('root')
);
You're repeatedly overwriting the bikeData state item:
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks;
networkData.map((data) => {
console.log(data)
this.setState({ // ***
bikeData: [data] // *** Here
}); // ***
})
})
It's not clear why you're using map there at all; certainly, map is the wrong tool if you're not going to return a value from the callback and not going to use the array map creates.
I can't say for sure, but it seems like you just want to use networkData directly:
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks;
this.setState({bikeData: networkData});
})
Note that I'm assuming you want to overwrite bikeData with the result, not add to it.
Or if you want to transform that data in some way, you'd use the result of map:
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks;
this.setState({
bikeData: networkData.map((data) => {
return /*...do something to data...*/;
})
});
})
(Same assumption.)
To add to bikeData, you'd need to use the callback form of setState:
this.setState(({bikeData}) => ({
bikeData: [...bikeData, ...networkData.map((data) => {
return /*...do something to data...*/;
})]
});
Also note that you have an error in your fetch call (you're not alone, a lot of people do this, so many I wrote it up on my anemic little blog): You haven't checked res.ok:
fetch('https://api.citybik.es/v2/networks')
.then(res => { // ***
if (!res.ok) { // ***
throw new Error(res.status); // ***
} // ***
}) // ***
.then(res => res.json())
.then(response => {
// ...
Try this:
componentDidMount() {
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks; //which is currently an array
this.setState({
bikeData: networkData
});
})
}
You are not recommended to do setState inside loop. So do setState outside the loop. Also the way you push data into array isn't correct. Try below solution
const bikeDataArray = this.state.bikeData;
networkData.map(data => {
console.log(data)
bikeDataArray.push(data);
})
this.setState({
bikeData: bikeDataArray
});