How do I grab this API data using ReactJS - json

Hi Could anyone help with this? I am trying to grab my API data from this API request but cannot seem to manage how to grab the bit I need.
Basically what I need to display in my <p></p> is this "astronomical": "0.4838725338",
Here is my json data
{
"links": {
"next": "https=DEMO_KEY",
},
"element_count": 6,
"near_objects": {
"2018-12-28": [
{
"links": {
"self": "x"
},
"id": "2450238",
"estimated_diameter": {
"kilometers": {
"estimated": 0.6089126221,
"estimatedmax": 1.3615700154
}
},
"is_potentially": false,
"approach": [
{
"date": "2018-12-28",
"epoch": 1545984000000,
"distance": {
"astronomical": "0.4838725338",
"lunar": "188.2264099121",
},
"orbitinody": "Nobes"
}
],
And here is my Component
class App extends Component {
state = {
data : []
}
componentDidMount() {
this.fetchasa();
}
fetchasa = () => {
fetch('https:?de_KEY')
.then((response) => response.json())
.then((result) => this.setState({
data: result.near_objects.2018-12-28.approach.distance[0]
}))
}
render() {
const {data} = this.state;
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Edit <code>src/App.js</code> and save to reload.</p>
<p>astronomical: {data}</p>
</header>
</div>
);
}
}
export default App;
Please help and thank you in advance :D

Try with:
result.near_objects['2018-12-28'][0].approach[0].distance.astronomical
If you don't know the index names of near_objects prior to the request, you can get the date value like this
const [first] = Object.keys(result.near_objects)
result.near_objects[first][0].approach[0].distance.astronomical

Related

React JSON is undefined

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>

How to use map on json response returned by a REST API with ReactJs

I've a json. The only thing I want is title from the json.
{
"projects": [
{
"id": 1,
"title": "Bike Servicing System",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 2,
"title": "Air Traffic Controller",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 3,
"title": "Program Counter",
"language": "JavaFX",
"requires": "JDK 8"
}
],
"profile": {
"name": "typicode"
}
}
I am using fetch and componentDidMount. I want to do it musing map method to iterate through. Though I don't need <ul> and <li> tags really. I will remove them later. My React code is
import React, { Component } from "react";
class ProjectStack extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json.projects
});
});
}
render() {
var { isLoaded, items } = this.state;
var i=0;
if (!isLoaded) return <div>Loading...</div>;
return (
<div>
<ul>
{
items.map(item => (
<li key={item[i++].id}>
Projects: {item[i++].title}
</li>
))
}
</ul>
</div>
);
}
}
export default ProjectStack;
Apparently, there is something that I don't know because I am getting this error.
PS: This question is different from mine
The JSON of the URL you are fetching is this:
[
{
"id": 1,
"title": "Bike Servicing System",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 2,
"title": "Air Traffic Controller",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 3,
"title": "Program Counter",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 4,
"title": "Dove Tail",
"language": "JavaFX",
"requires": "JDK 8"
}
]
So for correctly set the data in the state you need to:
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
});
});
}
Besides correcting the error they have already told you related the map loop.
I found 2 mistakes from your code.
The first one is you didn't check the response data.
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
console.log(json); // it is an Array not object.
this.setState({
isLoaded: true,
items: json
});
});
And the second is you didn't use the map() properly.
/*{
items.map(item => (
<li key={item[i++].id}>
Projects: {item[i++].title}
</li>
))
}*/
// items has objects, so you should use map() like this.
{
items.map(item => (
<li key={item.id}>
Projects: {item.title}
</li>
))
}
The below code is one way to achieve what you want.
class ProjectStack extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
console.log(json);
this.setState({
isLoaded: true,
items: json
});
});
}
render() {
const {
isLoaded,
items
} = this.state;
console.log(items);
if (!isLoaded) return ( < div > Loading... < /div>);
return ( <
div >
<
ul > {
items.map(item => ( <
li key = {
item.id
} > Projects: {
item.title
} < /li>
))
} <
/ul> <
/div>
);
}
}
ReactDOM.render( <
ProjectStack / > , document.getElementById('root')
)
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>

In a JSON file I need to access to an attribute name with ':' in it

I'm a react-native noob.
I need to read a link inside a JSON field called 'wp:featuredmedia.href'.
obviusly i can't put the ':' char in the code.
I've tried in this way... but I've no success :(
componentDidMount(){
const { navigation } = this.props;
const id = navigation.getParam('id', );
//const percorso = 'responseJson.wp:featuredmedia.rendered';
return fetch('https://www.seisnet.it/wp-json/wp/v2/posts/'+id)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
title: String(responseJson.title.rendered),
photos: String(responseJson.wp:featuredmedia),
}, function(){});
})
.catch((error) =>{
console.error(error);
});
}
EDIT 1
this is a section of the json file:
// 20190726085445
// https://www.seisnet.it/wp-json/wp/v2/posts/1967
"_links": {
"self": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/posts/1967"
}
],
"collection": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/posts"
}
],
"about": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/types/post"
}
],
"wp:featuredmedia": [
{
"embeddable": true,
"href": "https://www.seisnet.it/wp-json/wp/v2/media/1971"
}
],
"wp:attachment": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/media?parent=1967"
}
],
}
}
the field i've to read contains a link to another json file.
i've tried: JSONResponse_embedded["wp:featuredmedia"] and JSONResponse["wp:featuredmedia"]. the first give me the error "undefined is not an object" while the second give me nothing in output
Instead of responseJson.wp:featuredmedia, try responseJson["wp:featuredmedia"]
JavaScript object: access variable property by name as string

How to ignore a variable in JSON data in Angular TypeScript

I am facing a problem while reading a JSON file in angular 7.
below is the format of my JSON data file.
[
{
"attributes": {
"User": "jay"
}
},
{
"attributes": {
"User": "roy"
}
},
{
"attributes":{
"User": "kiya"
}
},
{
"attributes":{
"User": "gini"
}
},
{
"attributes": {
"User": "rock"
}
},
{
"attributes": {
"User": "joy"
}
}
]
here is my component.ts file method in which I am calling service for a JSON file.
this.rest.getUsers().subscribe((data: {}) => {
console.log(data);
this.items = data;
//this.items=data;
});
Here is my service.ts file method.
private extractData(res: Response) {
let body = res;
return body || { };
}
getUsers():Observable<any> {
return this.httpService.get('./assets/usersdetails.json').pipe(
map(this.extractData));
}
Now I want to read only User from the JSON file and I want to filter the word attributes. is there any way to filter this thing from JSON file, so that I can only get the User value. because in my Project this attributes in JSON is creating a problem and I want to ignore or filter this.
because in my application I need to read the JSON as below format.
[
{
"User": "jay"
},
{
"User": "roy"
},
{
"User": "kiya"
},
{
"User": "gini"
},
{
"User": "rock"
},
{
"User": "joy"
}
]
but the data is coming in the format as above mentioned JSON format with attributes
so is there any way to filter the extra attributes thing from the JSON at the time of reading.
You don't show the code for the extractData method, so it is hard to say what isn't working there, but you should be able to accomplish your goals with the following.
return this.httpService
.get('./assets/usersdetails.json')
.pipe(
map(data => data.map(d => d.attributes))
);
If there are other properties on 'attributes' and you really only want the 'user' data, then you could further update the code to:
return this.httpService
.get('./assets/usersdetails.json')
.pipe(
map(data => data.map(d => ({ 'User': d.attributes.User })))
);

Import JSON data in to array in REACTJS

So ive been looking at this for a couple hours now trying to get my head around it but I just cant figure it out.
I have a json file located at '/src/data/topbar.json' which i want to include in my topbar-container component which will be used to generate the top menu.
What am I doing wrong here?
topbar.json:
{
"topbarLinks": [
{
"id": 1,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-home",
"text": "home",
"link": "/"
},
{
"id": 2,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-euro",
"text": "Pricing",
"link": "/pricing"
},
{
"id": 3,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-exclamation-sign",
"text": "Help",
"link": "/help"
},
{
"id": 4,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-question-sign",
"text": "FAQ",
"link": "/faq"
},
{
"id": 5,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-edit",
"text": "Register",
"link": "/register"
},
{
"id": 6,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-share",
"text": "Login",
"link": "/login"
}
]
}
topbar-container.js
import React, { Component } from 'react';
import './topbar-container.scss';
import Link from '../topbar-link/topbar-link';
require ('../../data/topbar.json');
class TopbarContainer extends Component {
constructor() {
super();
this.State = {
topbarLinks: []
}
}
componentDidMount() {
fetch('../../data/topbar.json')
.then(results => {
return results.json();
}).then(data => {
let topbarLinks = data.results.map((topbarLinks, key) => {
return (
<Link
key={topbarLinks.id}
text={topbarLinks.text}
icon={topbarLinks.icon}
link={topbarLinks.link}
/>
)
})
})
}
render() {
return (
<div className="container-fluid header__topbar">
<div className="row">
<div className="container">
<ul className="header__topbar__list">
{this.state.topbarLinks}
</ul>
</div>
</div>
</div>
);
}
}
export default TopbarContainer;
You can't fetch a local JSON file, you either have to import it, or setup a webserver that will serve that JSON file
import myJson from '../../data/topbar.json';
Then just map over it and don't forget to setState
componentDidMount() {
let topbarLinks = myJson.topbarLinks.map((topbarLinks, key) => {
return (
<Link
key={topbarLinks.id}
text={topbarLinks.text}
icon={topbarLinks.icon}
link={topbarLinks.link}
/>
)
})
this.setState({topbarLinks: topbarLinks}); // <--
//or just this.setState({ topbarLinks });
}
and as somebody else noted this.state has to be lowercase
topbar.json:
export default {
"topbarLinks": []
}
then you can simply import it without fetch
import data from '../../data/topbar.json'
let topbarLinks = data.results.map((topbarLinks, key) => {
return (
;
I don't think that State should be capitalized in this.State in your constructor.
Change map function to data.topbarLinks.map to access json data.
let topbarLinks = data.topbarLinks.map((topbarLinks, key) => {
return (
<Link
key={topbarLinks.id}
text={topbarLinks.text}
icon={topbarLinks.icon}
link={topbarLinks.link}
/>
)
})
And then set state
this.setState({topbarLinks: topbarLinks});
Change your initial state as this.State to this.state in constructor.