I have this json file and I want to access the array that is inside this object:
best-sellers": [
{
"title": "Chuteira Nike HyperVenomX Proximo II Society",
"price": 499.90,
"installments": {
"number": 10,
"value": 49.90
},
"high-top": true,
"category": "society",
"image": ""
},
{
"title": "Chuteira Nike HyperVenom Phantom III Cano Alto Campo",
"price": 899.90,
"installments": {
"number": 10,
"value": 89.90
},
"high-top": true,
"category": "campo",
"image": ""
}
}
]
This is the code on my component:
ngOnInit(): void {
this.service
.lista()
.subscribe(chuteiras =>{
this.chuteiras = chuteiras;
})
}
and my template looks like this:
<div *ngFor="let chuteira of chuteiras.best-sellers">
But angular is not reconigzing it the `best-sellers", here's the error that I'm getting:
Cannot read property 'best' of undefined
Just use bracket notation,
<div *ngFor="let chuteira of chuteiras["best-sellers"]">
well,that's one way of doing it but angular 6 came with a simple solution. when i was faced with this problem i myself resolved to this solution but it didn't work for me so after searching and making my own touches i ended up with this solution.
1.create the function to receive the JSON data in my case i used a web API
getTrending() {
return this.http.get(https://api.themoviedb.org/3/trending/all/day?api_key=${this.api_key});
}
2.call the function in my case i used a service, so after import it to my component i simply added this
showPopular(): void {
this.api.getTrending().subscribe((data: Array<object>) => {
this.list = data['results'];
console.log(this.list);
});
}
as you can see the data variable only accessed the information i required.
Related
This is a repeatable component of strapi:
Api call:
{
"id": 1,
"attributes": {
../other fields
"imgs": [
{
"id": 37,
"title": "KeyNote Lecture",
"subtitle": "Felicitation in Chennai, Molaris 2022"
},
../Same Objects
],
}
}
See API call getting the only title, subtile, id only. but the image not getting.
Please, anyone, help.
this is because populate=* gives only first level of relations, and image inside component is a relation of second level:
Option one (easiest) use yarn add strapi-plugin-populate-deep
/api/course-director?populate=deep
Option two use qs:
const str = qs.stringify(
{
populate: { imgs: { populate: ["image"] } }
},
{ encodeValuesOnly: true }
);
populate[imgs][populate][0]=image
I designed an app using Angular which is linked to a DB using a backEnd made with ASP.NET
My problem is that my JSON in the Front is a little different that the JSON in the backEnd.
And I need help on how to map the frontEnd JSON to send it to the backEnd.
psd: i created all the interfaces on the frontend, and I'm usign formControls and FormArrays to store the data in the front, the problem is that de JSON are a bit different.
I cannot change the JSON on the backEnd because is linked with the DB and it has PK and FK so that's the reasson because it's a bit different.
I was thinking about doing something like this.myform.value and map to the other interface, but i have no idea on how to do that because i have array of arrays...
Maybe a for loop?
Here is my frontEnd JSON:
{
"non-array fields....................." : "bla bla",
"arraySustancias": [
{
"sustanciaActiva": "hello",
"contenido": "2",
"suministro": ["hello2","hello3"],
"unidades": "3"
}
],
"arrayProcedimientos": [
{
"procedimiento": "",
"fechaInicioProcedimiento": "",
"fechaFinProcedimiento": "",
"notasProcedimiento": "",
"arraySubprocedimientos": [
{
"subprocedimiento": "",
"fechaInicioSubProcedimiento": "",
"fechaFinSubProcedimiento": "",
"notasSubProcedimiento": "",
"exp": ""
}
]
}
]
}
And here is my backEnd JSON:
{
"non-array fields.....................": "bla bla",
"registros_arraySustancias": [
{
"registros_arraySustancias_suministro": [
{
"registros_arraySustancias_id": "",
"id": "",
"value": [
"ABBOTT LABORATORIES",
"ADAMA Agan Ltd."
]
}
],
"registros_id": "",
"id": "",
"sustanciaActiva": "hola",
"contenido": 2,
"unidades": 3
}
],
"registros_arrayProcedimientos": [
{
"registros_id": "",
"id": "",
"procedimiento": "text",
"fechaInicioProcedimiento": "18/06/2020",
"fechaFinProcedimiento": "18/06/2020",
"notasProcedimiento": "notes",
"registros_arrayProcedimientos_arraySubprocedimientos": [
{
"registros_arrayProcedimientos_id": "",
"id": "",
"subprocedimiento": "text",
"fechaInicioSubProcedimiento": "19/06/2020",
"fechaFinSubProcedimiento": "19/06/2020",
"notasSubProcedimiento": "notes"
}
]
}
]
}
Thanks for your help :)
In that case I think you have to work a little bit with angular forms so that data from frontend should be from the same structure. FormGroups and FormArayys will help you alot.
Try looking at this article as well.
http://www.howilearnt.com/web-development/angular/make-a-json-object-with-angular-forms/
You simply create an object from your original object. There is no magic or automatic way to do that. Example:
interface OriginalData {
foo: string;
baz: {
test: number[]
};
}
interface MyData {
foobar: string;
bazTest: number[];
}
function getData(): Observable<OriginalData> {
return this.http.get<OriginalData>(url);
}
function convertData(original: OriginalData): MyData {
const res: MyData = {
foobar: original.foo,
bazTest: original.baz.test
};
return res;
}
// somewhere in your code
getData().subscribe(
v => sendData(convertData(v))
);
I'm using the Angular http client here, because you added the tag "angular". It will give you an object of the type you specified.
That was what I was looking for:
mapeado = {
pais: "",
registros_arraySustancias: [{
unidades: "",
contenido: 2,
sustanciaActiva: "",
registros_arraySustancias_suministro: [{value: [""]}]
}
]
}
Thanks a lot for your help
From json I get this:
{
"name": "Leonardo",
"weapon": "sword"
},
{
"name": "Donatello",
"weapon": "stick"
},
{
"name": "Michelangelo",
"weapon": "nunchucks"
},
{
"name": "Raphael",
"weapon": "sai"
}
But for template I want to insert one extra field dynamically:
{
"name": "Leonardo",
"weapon": "sword"
"is_leader": "true"
},
{
"name": "Donatello",
"weapon": "stick"
"is_leader": "false"
},
{
"name": "Michelangelo",
"weapon": "nunchucks"
"is_leader": "false"
},
{
"name": "Raphael",
"weapon": "sai"
"is_leader": "false"
}
But I can't even get component to return the observable (says it's undefined, but renders ok in template). So far I have this in my component.
constructor(private dataService: DataService) {
this.dataSubscription = this.dataService.getTestData().subscribe(res => this.allData = res);
}
You should modify the data from .map()
Here is the logic how you can achieve that will current given code :
.subscribe(res => {
this.allData = res.map(e => {
e['is_leader'] = true; // as per your rule;
return e;
});
});
With HttpClient which came with Angular 4.3+, you could use interceptors (HttpIntercept) to intercept, filter and/or modify you incoming JSON feed. A bit of googling shows how to setup interceptors and use them like here for example.
I'm new with ReactJs and have this question which right now I find it a bit hard to understand.
I have a component which does a call to retrieve XML object, this XML object is later parsed to JSON object and after passed to other component in order to do some sorting to it.
Right now i'm stuck and unable to access properly the JSON on my second component.
And when I'm trying to do this.props.files.map - it says that map is undefined.
this is the parent component render method where I pass the properties:
render() {
return (
<div>
<List files={this.convertToJson()}/>
</div>
)
}
the JSON that I receive looks like this:
[ {
"$": {
"date": "",
"description": "",
"name": "",
"size": "107829",
"type": "pdf"
}
}, {
"$": {
"date": "",
"description": "",
"name": "",
"size": "682015",
"type": "pdf"
}
}
]
How should I write my second component to get access to this JSON data and later show all properties, i would like to iterate over it and have access to all properties.
this.props.files.map(function($) {
return <li key={$}>{$}</li>
})
this gives me an error with files.map is undefined.
i'm pretty new with this so all help would be useful.
here is the code for this.convertToJson() as requested, if I console log it - it looks like the JSON above.
convertToJson = () => {
return JSON.stringify(this.state.data)
I think the issue might actually be with this.convertToJson()
You need to parse the JSON object into a Javascript object in order to iterate over it in the way you are suggesting.
Check out this example it seems to work correctly.
// This is just mocking your JSON object
const json = JSON.stringify([{
"$": {
"date": "",
"description": "",
"name": "",
"size": "107829",
"type": "pdf"
}
}, {
"$": {
"date": "",
"description": "",
"name": "",
"size": "682015",
"type": "pdf"
}
}
]);
// This is what you care about
const obj = JSON.parse(json);
obj.map(o => {
// You need to get o.$ to get the actual object
console.log(o.$)
});
also in order to pass a component all of the objects properties as props you'll probably need the spread operator <li {...o.$}>{$}</li>
Hope this helps
I'm trying to implement a decoupled wordpress solution and I'm having a bit of confusion displaying the JSON object properties in my template. I'm able to return JSON objects for the WP API but not sure how to handle them. The only way I can get a property to display it's value in a template is if I add a [0] to the interpolated property, which won't work in an ngFor loop. I've read the solution by #Thierry here access key and value of object using *ngFor
but this doesn't seem to be how Google handles the Tour of Heroes app http://plnkr.co/edit/WkY2YE54ShYZfzJLSkMX?p=preview
Google uses this data set:
{
"data": [
{ "id": "1", "name": "Windstorm" },
{ "id": "2", "name": "Bombasto" },
{ "id": "3", "name": "Magneta" },
{ "id": "4", "name": "Tornado" }
]
}
which looks like a JSON object to me, so how is the app able to handle something like this:
<ul>
<li *ngFor="let hero of heroes">
{{hero.name}}
</li>
</ul>
I'm just unclear if there's been a change in RC5 that allows iteration over an object, or do I still need to transform this somehow. I'm very new to Angular and could use a little guidance on this matter. Thanks!!
An update based on the comments, if I want to transform an api request like http://localhost:8888/wp-json/wp/v2/posts, what's the best method for that? My return code would look something like:
[
{
"id": 4,
"date": "2016-08-09T00:09:55",
"date_gmt": "2016-08-09T00:09:55",
"guid": {
"rendered": “http://localhost:8888/?p=4"
},
"modified": "2016-08-09T00:11:05",
"modified_gmt": "2016-08-09T00:11:05",
"slug": “wp-api-test”,
"type": "post",
"link": "http://localhost:8888/2016/08/wp-api-test”,
"title": {
"rendered": "testing the wp api"
},
"content": {
"rendered": "<p>loreum ipsum</p>\n"
},
"excerpt": {
"rendered": "<p>loreum ipsum</p>\n"
},
"author": 1,
"featured_media": 0,
"comment_status": "open",
"ping_status": "open",
"sticky": false,
"format": "standard",
"categories": [
1
],
}
]
Without writing all the code for you, there is no short answer to what you are asking, but here are some tips:
You have to take the JSON response you are getting back and create either an interface or class in TypeScript so when you perform the POST, Angular 2 can take the JSON and convert it to an object using your classes.
JSON to TS generator: http://json2ts.com/
Ninja Tips 2 - Make your JSON typed with TypeScript - http://blog.ninja-squad.com/2016/03/15/ninja-tips-2-type-your-json-with-typescript/
TypeScript Json Mapper - http://cloudmark.github.io/Json-Mapping/
How are you defining your services?
Here's an example:
export interface IPost {
id: number;
date: Date;
date_gmt: Date;
... // rest of your defintion
}
#Injectable()
export class BlogPostService {
private http: Http;
constructor(http: Http) {
this.http = http;
}
private apiUrl: string = 'api/blog/posts.json';
getPosts(): Observable<IPost[]> {
return (this.http.get(this.apiUrl)
.map((response: Response) => <IPost[]>response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError)) as any;
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || "Server error");
}
}
This line should transform your json object to array[] of IPosts
.map((response: Response) => <IPost[]>response.json())
Hope that helps.
Thanks so much for the answers. They helped lead me to the solution. I was able to solve this rather simply by creating a posts array and making it equal to the Observable return. The component looks like this:
posts: {};
constructor (private _wpService: WpApiService) {}
ngOnInit() { this.getPosts() }
getPosts() {
this._wpService.getPosts()
.subscribe(
data => {
this.posts = data;
});
}
The template looks like:
<li *ngFor="let post of posts">
<h3>{{post.title.rendered}}</h3>
</li>
Just replace {{hero.name}} by {{hero.data.name}}
The best way to handle the JSON object by creating an interface class to access the data easily