Angular2, get data from REST call - json

I'm triyng to get data from json file by a id, by I'm getting all the content.
Here the JSON:
[
{ "id": "1", "name": "Carlos", "apellidos":"López", "edad":"30", "ciudad":"Hospitalet" },
{ "id": "2", "name": "Arantxa", "apellidos":"Pavia", "edad":"24", "ciudad":"Barcelona" },
{ "id": "3", "name": "Didac" , "apellidos":"Pedra", "edad":"muchos", "ciudad":"Cornellà" },
{ "id": "4", "name": "Daniel" , "apellidos":"Farnos", "edad":"nolose", "ciudad":"Barcelona" }
]
Service:
private usersUrl = 'app/users.json';
getUser(id: String): Observable<User>{
let body = JSON.stringify(
{
"token": "test",
"content": {
"id": id
}
}
);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers,
body : body
});
return this.http.get(this.usersUrl, options)
.map(res => res.json()).catch(this.handleError);
}
Angular Component:
ngOnInit(){
this.route.params.subscribe(params => {
let id = +params['id'];
this.apiService.getUser(id).subscribe( (res) => { console.log(res); } );
})
}
Console.log:
Array[4]0: Object1: Object2: Object3: Objectlength: 4__proto__: Array[0]
Is the JSON bad?
Thanks.

Because you didn't filter the result by id.
.map(res => res.json())
.map(x > x.find(x => x.id == id) // filter by selected id
.catch(this.handleError);

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>

Iterate a JSON array by a key value in react-native

Is there anyway to get a value in an object from a json array. I need to get a value from an object based on another value.
I have my code like:
export default class StandardComp extends Component {
constructor(props) {
super(props)
this.state = {
id: '',
email: 'abc#gmail.com',
dataSource: []
};
}
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({dataSource: responseJson})
//dunno what to do here
})
.catch((error) => {
console.error(error);
})
}
}
My "responseJson" is something like this. Then providing the key value (abc#gmail.com), how could I get the string "abcdef"?
[
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
}
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
]
Thank you in advance.
Find the element that matches email and return the id.
array::find
const data = [
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
},
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
];
const findIdByEmail = (data, email) => {
const el = data.find(el => el.email === email); // Possibly returns `undefined`
return el && el.id; // so check result is truthy and extract `id`
}
console.log(findIdByEmail(data, 'cat#gmail.com'));
console.log(findIdByEmail(data, 'abc#gmail.com'));
console.log(findIdByEmail(data, 'gibberish'));
The code will depend on how you get the value abc#gmail.com.
You'll probably need to pass it in as an argument to componentDidMount via a prop? Or extract it to a separate function. It just depends.
Something like this is the most basic way I'd say.
const value = responseJson.filter(obj => obj.email === 'abc#gmail.com')[0].id
Here it is implemented in your class.
export default class StandardComp extends Component {
...
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ dataSource: responseJson })
const { email } = this.state
const value = responseJson.filter(obj => obj.email === email)[0].id
})
.catch((error) => {
console.error(error);
})
}
}

Try to get key values recursively from JSON in Angular 5

I want to retrieve all the key values from a JSON file. For example in :
{
"total_count": 6,
"incomplete_results": false,
"items": [
{
"url": "https://api.github.com/repos/Samhot/GenIHM/issues/6",
"id": 293237635,
"number": 6,
"title": "Rechercher des documents",
"user": {
"login": "Samhot",
"id": 7148311
]
}
I would like to get :
["total_count", "incomplete_results", "items", "url", "url", "number", "title", "user", "login", "id"]
I have a function which return the content of my JSON in an observable :
getConfig(): Observable<any> {
return this.http.get<any>(this.myURL);
}
After that the data are reformated with .map to get only the keys with the Object.keys() function :
merge()
.pipe(
startWith({}),
switchMap(() => {
return this.getConfig();
}),
map(data => {
return Object.keys(data.items[0]);
}
)
)
.subscribe(data => {
this.dispo = data;
});
My problem is that i get only the keys that are in the level of the JSON I told
(data.items[0]) and not the ascendants or the descendants.
Of course I can create multiple requests but it asks to know in advance the structure of the JSON, what I want is to make it generic ...
How can I do to have an array with with all of my keys regardless of the structure of the JSON ?
Thanks in advance !
You would need to do a recursive function like:
function getDeepKeys(obj) {
const keys = Object.keys(obj);
const childKeys = keys
.map(key => obj[key])
.map(
value =>
Array.isArray(value)
? getDeepKeys(value[0])
: typeof value === "object"
? getDeepKeys(value)
: []
)
.reduce((acc, keys) => [...acc, ...keys], []);
return [...keys, ...childKeys];
}
const obj = {
total_count: 6,
incomplete_results: false,
items: [
{
url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
id: 293237635,
number: 6,
title: "Rechercher des documents",
user: {
login: "Samhot",
id: 7148311
}
},
{
url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
id: 293237635,
number: 6,
title: "Rechercher des documents",
user: {
login: "Samhot",
id: 7148311
}
}
]
};
console.log(getDeepKeys(obj));
Which then you would use like map(getDeepKeys). Note that this function assumes all the items in your array have the same schema.

Angular 4 find JSON data

I have this JSON: (this.url)
{
"user": [
{
"id": "1",
"name": "root",
"password": "root"
},
{
"id": "2",
"name": "clienttest",
"password": "123456"
}
]
}
and I have this service:
findUsers(id: number) : boolean {
return this.http.get(this.url)
.map((res: Response) => res.json());
.someOperator(to assert the id exist)...
}
I want to return true if the user was found.
Is there some operator like filter that can make this assert for me?
try to use Array.some() method:
findUsers(id: number) : boolean {
return this.http
.get(this.url)
.map((res: Response) => {
let result = res.json();
return result.user.some(user => parseInt(user.id) === id)
})
}
Inline simulation:
const data = {
"user": [
{
"id": "1",
"name": "root",
"password": "root"
},
{
"id": "2",
"name": "clienttest",
"password": "123456"
}
]
}
// this will simulate http get resolve being processed by res.json()
const httpGet = Rx.Observable.of(data);
const findUsers = id =>
httpGet.map(data => data.user.some(user => parseInt(user.id) === id))
;
findUsers(1).subscribe(result => console.log(result));
findUsers(3).subscribe(result => console.log(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>

Render HTTP-Response as a list in Angular2

I have a json response like this.
{
"response": {
"data": {
"customers": [{
"customerNumber": "123",
"customerName": "ABC",
"customeraddresse": [{
"address": "test"
}]
}, {
"customerNumber": "345",
"customerName": "CDS",
"customeraddresse": [{
"address": "test1"
}]
}]
}
}
}
I am doing a request like this to get the response data. And it will be returned, as I already checked.
public getData(): Promise<any> {
let payload = JSON.stringify( ... );
let headers = new Headers({ 'Content-Type': 'application/json'});
return this.http.post(this.url, payload, { headers: headers })
.toPromise()
.then(res => {
this.response_data = res.json().response.data;
return this.response_data;
})
.catch(this.handleError);
}
But the problem is, that I want to get the value of customerNumber and customerName, and display them in a list
In this example, there are two customers, so this markup should be rendered two times:
<div>
<div>CustomerNumber</div>
<div>CustomerName</div>
</div>
You should use an *ngFor loop.
In your template:
<div *ngFor="let customer of response_data.customers">
<div>{{customer.customerNumber}}</div>
<div>{{customer.customerName}}</div>
</div>