How to get json file local and repeat data? - json

I am new in angular5 and I am trying to load json file and repeat it but I can't repeat data
( i can get and show data form jason file but can't repeat data )
in src/assets/data.json
{ "status": "S","messeage": "error","Card":[
{
"ID": "01",
"Price": "30,000",
"Color": "Black"
},
{
"ID": "02",
"Price": "32,000",
"Color": "Red"
}]}
in src/app/app.component.ts
data;
constructor(private http:Http) {
this.http.get('../assets/data.json')
.subscribe(res => this.data = res.json());
}
in src/app/app.component.html
{{data?.Card[0].Color}} // => black
{{data?.Card[0].Price}} // => 30,000
But I need to know how to repeat it.
Sorry for my english
Thank you for help
Edit
last 2 answer it work
but it have error in console
how to fix it ?
thank you so much
enter image description here

Now you get your json .
You can repeat it like this
In js code .
for(i=0;i<data.Card.length;i++){
console.log(data.card[i].Color);
}
In angular5 html template
<li *ngFor="let card of data.Card">
{{ card.Color}}
</li>

You can use *ngFor directive into template to repeate it.
example <div *ngFor="let obj of data.Card">
<div>{{obj.Color}}</div>
<div>{{obj.Price}}</div>
</div>

Related

JSON Object Access from Response

[
{
"productName": "saree",
"productDescription": "bomkai saree",
"productDiscountPrice": 12000,
"imageUrl": "drdrfd",
"productActualPrice": 12400,
"productImages": [
{
"id": 10,
"name": "Screenshot from 2022-09-05 18-27-38.png",
"type": "image/png",
"picByte": "3B0JoYZ1QGDSDBwyYAP0p4AgqrkuCDxrnc4dx3KCk4kHrj3rRbY3EgluN4exFo2KYC4pdyHuuog3KfVIPlDWvoS1uGO8T1nVByTumaZbzz/PYNA7DacA8zbANn4tGqDy2IQ563ZKYGxgkdA1DdNNjFlwzn6k+OO4Hjj27mAqXhcbyvg+SVoaYpDOGcyemBNINSGCd4UOLuvN5fjzXW08cNM95EULIhse4yDHWaFt+Rts6HHWXWgPrusOJ+YfGTI3/A4U7lzwWAyjoAAAAAElFTkSuQmCC"
}
],
"id": 22
}
]
how i can Access picByte from angular UI,
i got response from the api with list of obect inside other object like i mentioned here ,the productImages is a seperate list i need productImages.picByte value to set inside image tag to make a view ,how can i do it? with a for loop or any thing? please help(https://i.stack.imgur.com/x0a6e.png)](https://i.stack.imgur.com/Ib8vA.png),i need to shoe these byte inside my image tag for display the images,
You should be able to easily just loop through the results in your html as so:
<div *ngFor="let data of myObject">
<p>Id: {{data.id}}</p>
<img
*ngFor="let images of data.productImages"
[src]="getImageSrc(images.picByte)"
width="250px"
height="250px"
/>
</div>
Where myObject is your apiResponse. getImageSrc is defined in the component code as:
getImageSrc(image: string) {
return 'data:image/png;base64, ' + image;
}

how to map in jsx a json string that has image and text information

i have a json file containing array of object such that:
[
{
"id": 1,
"title": "first title",
"description":"first descript",
"image":"/assets/Images/myimage-1.jpg"
},
{
"id": 2,
"title": "second title",
"description":"second descript",
"image":"/assets/Images/second.jpg"
},
]
i have the following function in jsx
export default function myfunc({task}) {
return (
<ul>
{tasks.map(task => <div key={task.id} >{task.title}{task.description}</div> )} ;
{tasks.map(task => <img src={task.image} key={task.id}></img> )}
</ul>
)
}
which when executed parses the text content first then the image content, due to the need for img tag
how can i make it so that it is parsing the image source and text in one go using map? while being able to assign classes to them?
i found a similar question from years ago but that one is unanswered as well. React dynamic mapping image paths from json
Here you go
First, I've created a one js file which map all the image files that I want to use, something like
export default {
"1.png": require("./1.png"),
"2.png": require("./2.png")
};
Then, next step,I've imported the mapping file and change json a bit
import images from "./assets"; // <----- imported
const tasks = [
{
id: 1,
title: "first title",
description: "first descript",
image: "1.png" // <------- changed here
},
{
id: 2,
title: "second title",
description: "second descript",
image: "2.png" // <------- changed here
}
];
Final Step :
{tasks.map(task => (
<img alt="" width="250"
src={images[task.image]} // <----- HERE
key={task.id} />
))}
WORKING DEMO :

fetching and displaying the backend json data as dropdown in an Ionic project

Iam working in an ionic project, where my requirement is to get the backend json data through an api call and display the json content as dropdown in front end. below is the api call code,json format and code i tried.
Broker api call
http://example.com/broker/get-user-names
backend Json data:
{
"USER_NAME": "John",
"USER_COUNTRY": "USA"
},
{
"USER_NAME": "Smith",
"USER_COUNTRY": "Canada"
},
{
"USER_NAME": "Peter",
"USER_COUNTRY": "Russia"
},
I wanted to create a dropdown where i want to get all the usernames in dropdwon to select, i have created a method in .ts files, below the method
getUserNames() {
this.apiService.getUserNames(this.apiService.loggedInUser.value.id).then(
res => {
this.userNames= res;
alert(JSON.stringify(this.userNames));
},
err => {
alert(JSON.stringify(err))
}
)
}
In .html file
<ion-select placeholder="Select One">
<ion-select-option selected="true" >{{userNames.USER_NAME}}-</ion-select-option>
</ion-select>
But its displaying only the first user name i.e JOHN in my case as json data contains john as first username.
How can i do to display all the usernames as dropdowns from the backend json data.
please help me on this , i got struck in this from last 1 week.
thanks
Provided this.userNames is an array, use:
<ion-select-option *ngFor="let user of userNames">{{user.USER_NAME}}-</ion-select-option>
.ts
Create an array to hold the data you get from the API
userNames = [];
now in the subscription block:
getUserNames() {
this.apiService.getUserNames(this.apiService.loggedInUser.value.id)
.subscribe(res => {
this.userNames= res;
alert(JSON.stringify(this.userNames));
},
err => {
alert(JSON.stringify(err))
}
)
}

Show in Html a JSON file in Angular

I'm trying to print a JSON (link to the JSON) in an html file.
JSON:
{
"ricette": {
"FRIGGITRICI": {
"Alici": [
[
{"500": "scongelamento"}
],
[
{"60": "nada"}
]
],
"BaccalĂ ": [
[
{"500": "scongelamento"}
],
[
{"210": "immerso"},
{"210": "cestello su"},
{"30": "immerso"}
]
]
},
"GRIGLIA": {
"BaccalĂ ": [
[
{"500": "scongelamento"}
],
[
{"210": "immerso"},
{"210": "cestello su"},
{"30": "immerso"}
]
]
}
}
}
I've fetched it and saved in a variable:
export class DatiService {
fileJson: JSON;
constructor() { }
private datiUrl = 'https://api.myjson.com/bins/zbfh5';
async getDati(){
await fetch(this.datiUrl)
.then(res => res.json())
.then((out) => {
this.fileJson=out;
});
console.log(this.fileJson);
};
}
How can i print it in the html code?
Can i just use de "." to enter in its fields?
Or it's more complicated?
You can use the JsonPipe in your template.
{{fileJson | json}}
If you want to print a specific part you can navigate via . deeper into the object structure.
{{fileJson.ricette.FRIGGITRICI | json}}
If you want to print a primitiv value interpolation is enough and no json pipe is needed.
{{fileJson.version}}
UPDATE
Did you called your getDati function? Add an ngOnInit Lifecycle Hook and call it there. Here is an working stackblitz sample.
I just realized it's a service in your sample code. Take the service and inject it into a component and call it there.
We can use pre tag to view JSON data in HTML
Pass your JSON in var data.
And Set pre tag in HTML body.
var data = {Your JSON Object}
$("#json").innerHTML = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

How to parse a JSON object from an external file in React using .map() in ES6 and a loop?

I am trying to import a JSON object which is in an external file using React, and display its content inside a loop containing HTML. The goal is to display all that into a JQuery Slider (Slick).
I think I succeeded in importing the JSON, but I can't display it. Most of the results I find on the internet are in ES5 also.
Here is my slider.js file:
import React from 'react';
import slidesData from './slides.json';
export class Slider extends React.Component {
constructor(){
super();
this.state = {
slides: slidesData,
}
}
render() {
const list = this.state.slides.map(d => <div className="classTest">ID HERE {slidesData.id} - DESCRIPTION HERE {slidesData.desc}</div>);
return (
<div className="carousel">
<div className="data">
<div>list before {list} list after</div>
</div>
</div>
);
}
}
slides.json:
[
{
"id": 1,
"desc": "text desc 1"
},
{
"id": 2,
"desc": "text desc 2"
},
{
"id": 3,
"desc": "text desc 3"
},
{
"id": 4,
"desc": "text desc 4"
}
]
Result in the browser:
list before
ID HERE - DESCRIPTION HERE
ID HERE - DESCRIPTION HERE
ID HERE - DESCRIPTION HERE
ID HERE - DESCRIPTION HERE
list after
The files are in the same folder.
So the {list} is displayed 4 times (like the items it contains) but it doesn't display the content. What am I missing?
And then, I would like to repeat each <div className="data"> with a for loop displaying every time the JSON has content but until I find why the json is not getting displayed properly I don't want to try more complicated code.
Thanks =)
You are accessing the wrong object in your .map(). You should access d instead of slidesData:
render() {
const list = this.state.slides.map((d, index) => <div className="classTest" key={index}>ID HERE {d.id} - DESCRIPTION HERE {d.desc}</div>); //changed
return (
<div className="carousel">
<div className="data">
<div>list before {list} list after</div>
</div>
</div>
);
}
EDIT
You should also provide a key to your tags within the .map(). I edited my original answer.
From the looks of it your map is referencing 'd', but you're trying to access via {slidesData.id}
try:
const list = this.state.slides.map(d => return (<div
className="classTest">ID HERE `${d.id}` - DESCRIPTION HERE `${d.desc}`</div>));