not able display data json - json

My data format is :
{
"_id": "593994b7163e6b0011c738cb",
"location_id": "58ec522a99da86001123ec47",
"customer_id": "premiereservices",
"user": {
"phone_num": "8587366808",
"balance": 98.05
},
"cart_total": 3,
"shopping_cart": {
"items": [
{
"barcode": "611269101713",
"description": "Red Bull Sugar Free 8.4oz",
"price": 3,
"taxable": false,
"tax_collected": 0
}
]
},
"Date": "2017-06-08T12:17:27.039Z",
"__v": 0
}
I am not able iterate data from "shopping_cart" and "user" need help on this issue.
Thanks.

to extract data from shopping_cart has items array so you will need a for loop here
For example:
let a = {
"shopping_cart": {
"items": [
{
"barcode": "611269101713",
"description": "Red Bull Sugar Free 8.4oz",
"price": 3,
"taxable": false,
"tax_collected": 0
}
]
}
}
if(a.shopping_cart.items.length) {
for(let i: number = 0; i < a.shopping_cart.items.length; i++) {
console.log(a.shopping_cart.items[i].barcode);
console.log(a.shopping_cart.items[i].description); /* etc you can here */
}
}
to extract data for user
let a = {
"user": {
"phone_num": "8587366808",
"balance": 98.05
},
}
console.log(a['user']['phone_num']) /* etc you can here */

Thanks all for your help.This is working for my requirement.
Here is working code:
import {Component} from 'angular2/core'
#Component({
selector: 'my-app',
template: `
<ul *ngFor="let object of data">
<li>
<ul *ngFor="let value of of ObjectKey(object)"><li> {{value.phone_num}}</li> </ul>
</li>
<li>
<ul *ngFor="let value1 of of ObjectKey(object.shopping_cart.items)"><li> {{value1.barcode}}</li> </ul>
</li>
</ul>
`,
directives: [],
styles: [`
`]
})
export class App {
ObjectKey(obj){
return Object.keys(obj).map((key)=>{ return obj[key]});
}
}

If it is json encoded then decode it pls..
Then
foreach(data.shopping_cart as item)
{
barcode=item[0]["barcode"];
description=item[0]["description"];
}
0 is the index

Create data.model.ts
import { User } from './user.model';
import { ShoppingCart } from './shopping-cart.model';
export class Data {
_id: string;
location_id: string;
customer_id: string;
user: User;
cart_total: number;
shopping_cart: ShoppingCart;
Date: string;
__v: number;
}
Create user.model.ts
export class User {
phone_num: string;
balance: number;
}
Create shopping-cart.model.ts
import { Item } from './item.model';
export class ShoppingCart {
items: Item[];
}
Create item.model.ts
export class Item {
barcode: string;
description: string;
price: number;
taxable: boolean;
tax_collected: number;
}
Then
let str: string = 'your json string';
let data: Data = JSON.parse(str);
console.log(data.user);
data.shopping_cart.items.forEach(item => {
console.log(item);
});

are you using android studio? If so I might be able to help I have been asking similary questions for 2 days now. we need more info but, your first step is probably going to be creating a json array to store the info like "JSONArray arr= new JSONArray(in here put your josn condition object, followed by a .toString() method)

Related

Angular 13 - How to get pager details from the JSON response

I work on Angular 13 and I face an issue in that I can't retrieve pager data from the JSON.
The items array returned success but I can't return pager details.
So how to do it?
{
"items": [
{
"id": 3,
"itemNameER": "قلم",
"itemNameEN": "pen",
"description": "1"
},
{
"id": 4,
"itemNameER": "قلم",
"itemNameEN": "pencil",
"description": null
},
{
"id": 5,
"itemNameER": "قلم",
"itemNameEN": "pen2",
"description": null
},
{
"id": 8,
"itemNameER": "car",
"itemNameEN": "car",
"description": "1"
},
{
"id": 9,
"itemNameER": "mobile",
"itemNameEN": "mobile",
"description": "1"
}
],
"pager": {
"numberOfPages": 2,
"currentPage": 1,
"totalRecords": 6
}
}
What I had try is:
items?:ItemsData[];
export interface ItemsData {
id:number;
itemNameER:string;
itemNameEN:string;
description:string;
}
retrieveAllItems(pageNumber: number = 0): void {
this.erpservice.getAll(pageNumber)
.subscribe(
data => {
this.items=data.items;
console.log(data);
},
error => {
console.log(error);
});
}
How to extract pager data from JSON for the numberOfPages, currentPage and totalRecords?
Updated post
This is the information for the getAll return type.
So how to get pager data details?
export interface DataWrapper {
items: ItemsData[];
}
getAll(pageNumber: number): Observable<DataWrapper> {
let params = new HttpParams();
if (pageNumber)
params = params.append('pageNumber', pageNumber);
let httpOptions = {
params: params
};
return this.http.get<DataWrapper>(baseUrl,httpOptions);
}
What I had try is:
pager: any;
this.pager = data.pager;
But I get an error:
Property 'pager' does not exist on type 'DataWrapper'.ts(2339)
<ul>
<li *ngFor="let item of items | paginate: { currentPage:pager.currentPage }; let i = index">
{{ pager.numberOfPages * (pager.currentPage - 1) + i }}
</li>
</ul>
The error message is quite clear. The DataWrapper interface doesn't have a pager property.
You need to:
Add the pager property into DataWrapper interface.
Define the IPager interface.
export interface DataWrapper {
items: ItemsData[];
pager: IPager;
}
export interface IPager {
numberOfPages: number;
currentPage: number;
totalRecords: number;
}

How to use JSON data obtained with interface

I am trying to create an accordion from the JSON data.
I am calling the GET request from json-server and successfully able to call the API.
I am not able to access the properties of the children in the variable tileData which shows the error:
Property 'children' does not exist on type 'Tile[]'.
Not sure where I am going wrong.
tileData!: Tile[];
getTileData() {
this.tileService.showTile().subscribe((data: any) => {
this.tileData = data;
console.log('this.tileData.children.name :>> ', this.tileData.children.name ); //Shows error
});
}
The function in service file is
showTile() {
return this.http.get<Tile[]>('http://localhost:3000/data');
}
I have created an interface to store the obtained JSON data which is shown below:
export interface Tile {
name: string;
image: string;
children: { name: string; image: string; url: string };
}
My JSON data received as follows:
{
"data": [
{
"name": "First",
"image": "https://img.freepik.com/free-vector/football-2022-tournament-cup-background_206725-604.jpg?size=626&ext=jpg",
"children": [
{
"name": "Firstone",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
},
{
"name": "Firsttwo",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
},
{
"name": "Firstthree",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
}
]
},
{
"name": "Second",
"image": "https://img.freepik.com/free-vector/football-2022-tournament-cup-background_206725-604.jpg?size=626&ext=jpg",
"children": [
{
"name": "Secondone",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
},
{
"name": "Secondtwo",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
},
{
"name": "Secondthree",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
}
]
}
]
}
Issue 1
Your JSON response was an object containing the data property with Tile[].
Use map from rxjs to return as Observable<Tile[]>.
import { map } from 'rxjs';
showTile() : Observable<Tile[]> {
return this.http.get<any>('http://localhost:3000/data')
.pipe(map((response: any) => response.data));
}
Issue 2
While the children property is an array but not an object.
export interface Tile {
name: string;
image: string;
children: { name: string; image: string; url: string }[];
}
Issue 3
To print out the name, you need to iterate titleData and iterate children array from each title object.
getTileData() {
this.tileService.showTile().subscribe((data: any) => {
this.tileData = data;
for (let title of this.tileData) {
for (let child of title.children) {
console.log('title.children.name :>> ', child.name);
}
}
});
}
Demo # StackBlitz
You haven't mentioned the error but, the interface definition should use exact name as you have in data.
try
export interface Tile {
name: string;
image: string;
children: { name: string; image: string; url: string };
}

Mapping between two different Angular models

I'm trying to map Order.ts to OrderAction.ts, but getting the error Cannot ready property '0' of undefined. This error is coming up when I try to map the Order properties to OrderAction properties.
Here is Order.ts:
export class Order {
OrderId: number;
FunctionStatusList?: OrderFunctionStatus[];
}
export class OrderFunctionStatus {
FunctionTypeCode: number;
AvailableActions: OrderAvailableAction[];
}
export class OrderAvailableAction {
ActionLabel: string;
ActionValue: string;
}
Here is OrderAction.ts:
export class OrderAction {
FunctionTypeCode: number;
SelectedAction: string;
OrderList: AvailableAction[];
}
export class AvailableAction {
OrderId: number;
IsAvailableAction: boolean;
AvailableActions?: OrderAvailableAction[];
}
Here is the code that I wrote:
orders: any[] = [];
orderActionList: any[] = [];
ngOnInit() {
this.orders = this.orderService.getCheckedOrders();
this.orders.forEach((order: Order, i) => {
let orderAction: OrderAction = new OrderAction();
orderAction.OrderList[i].OrderId = order.OrderId;
orderAction.FunctionTypeCode = order.FunctionStatusList[i].FunctionTypeCode;
orderAction.AvailableActions = order.FunctionStatusList[i].AvailableActions;
orderAction.IsAvailableAction = order.FunctionStatusList[i].AvailableActions.length > 0 == true || false;
this.orderActionList.push(orderAction);
});
}
Here is a sample of the Order.ts json:
{
"OrderId": "1",
"FunctionStatusList": [{
"FunctionTypeCode": "1",
"AvailableActions": [{
"ActionLabel": "1",
"ActionValue": "1"
}]
}]
}
Here is a sample of the OrderAction.ts json:
{
"FunctionTypeCode": "1",
"SelectedAction: "1",
"OrderList": [{
"OrderId": "1",
"IsAvailableActionsLoaded": "1",
"AvailableActions": [{
"ActionLabel": "1",
"ActionValue": "1"
}]
}]
}
I'm not sure where exactly you're getting the error, but I did the following and it converts Order to OrderAction: https://plnkr.co/edit/VEHAdk3qPRIFkEAU?preview
The meat of the code is this:
this.orders.forEach((order: Order, i) => {
this.orderActions.push({
FunctionTypeCode: order.FunctionStatusList[i].FunctionTypeCode,
SelectedAction: null,
OrderList: [
{
OrderId: order.OrderId,
IsAvailableActionsLoaded:
order.FunctionStatusList[i].AvailableActions.length > 0,
AvailableActions: order.FunctionStatusList[i].AvailableActions,
},
],
});
});
I left SelectedAction as null because it was unclear how this value would be set.

recuperate fields of a json

I have a json like this :
[ {
"id": 1,
"libraryName": "lib1",
"bookName": "book1",
"bookPrice": 250.45,
"unitSold": 305
},
{
"id": 2,
"libraryName": "lib1",
"bookName": "book2",
"bookPrice": 450.45,
"unitSold": 150
},
{
"id": 3,
"libraryName": "lib1",
"bookName": "book3",
"bookPrice": 120.25,
"unitSold": 400
}]
I want to recuperate all the bookNames of this json in a list without creating the method getBookNames (because I want a standard way for any field of the json)
So, in the component.ts I used :
sales:any;
getSale () {
this.service.getSales().subscribe(data=> {this.sales = data,
console.log(this.sales.bookName)
})
}
It gives me undefined object in the console ! How can I solve this without creating a method getBookNames() ?
This is my class :
export interface Sale {
id: number
bookname : string
Libraryname: string
Bookprice : number
Unitsold : number
}
This is my service:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Sale } from './Sale';
#Injectable({
providedIn: 'root'
})
export class MyserviceService {
constructor(private http: HttpClient) { }
getSales () {
return this.http.get<Sale>("http://localhost:8081/sales/all")
}
}
The data obtained from the API is an array. So you could use array map() function to obtain a list of all the properties from the elements. Try the following
sales: any;
unitsSold = [];
getSale () {
this.service.getSales().subscribe(data=> {
this.sales = data,
console.log(data.map(item => item.bookName)); // <-- output: ['book1', 'book2', 'book3'];
console.log(data.map(item => item.id)); // <-- output: [1, 2, 3];
this.unitsSold = data.map(item => item.unitSold); // <-- [305, 150, 400]
});
}
I don't see anything lost here to recuperate.

best JSON Structure and getData() in Service using Interfaces & Models for Nested JSON

I have tried to find solutions that I can understand with my knowledge level. But without success. I hope that others can benefit from this question.
Currently I am trying to understand how I provide data from different nested JSON files via interfaces and models. For my example, let's say I plan to have 3 JSON files in the future. (items.json, characters.json, monsters.json)
First, I'd like to find out what a clever JSON structure looks like. (There are many example tutorials, but I did not find any for such a special case as mine)
Wich one is smarter?
First variant:
{
"wearable": {
"torso": [
{
"name": "Schlachtrobe",
"defense": 7,
"price": 22
}
],
"head": [
{
"name": "stirnband",
"defense": 2,
"price": 50
}
],
"wrist": [
// etc...
]
},
"weapons": [
// etc...
],
"consumables": [
{
"name": "Bonbon",
"effect": "Heilt um 100 TP"
},
{
"name": "Schokolade",
"effect": "Heilt um 250 TP"
}
]
}
Second variant:
[
{
"id": 1,
"category": "wearable",
"type": "torso",
"name": "Schlachtrobe",
"defense": 7,
"price": 22
},
{
"id": 2,
"category": "wearable",
"type": "head",
"name": "stirnband",
"defense": 2,
"price": 50
},
{
"id": 3,
"category": "consumables",
"name": "Bonbon",
"effect": "Heilt um 100 TP"
},
{
"id": 4,
"category": "consumables",
"name": "Schokolade",
"effect": "Heilt um 250 TP"
}
]
The second variant makes it easier to attach items (for example in the future monsters.ts) to other items. In this case, e.g. just attach the id numbers. But then each item must use the same interface structure ... Then, for example, the "Bonbon" of the category "consumable" always has an empty number field called "defense" And this is just a similiar example. There will certainly be many more empty fields.
And what is about the interfaces and the Models? I try to solve this like this:
items.interface.ts
export interface ItemsInterface {
}
export interface ArmorsInterface {
name: string;
defense: number;
price: number;
}
export interface ConsumablesInterface {
name: string;
price: number;
effect: string;
}
item.model.ts
export class ItemsModel implements ItemsInterface {
}
export class ArmorsModel implements ArmorsInterface {
name: string;
defense: number;
price: number;
constructor(obj?: any) {
this.name = (obj && obj.name) ? obj.name : '';
this.defense = (obj && obj.defense) ? obj.defense : '';
this.price = (obj && obj.price) ? obj.price : '';
}
}
export class ConsumablesModel implements ConsumablesInterface {
name: string;
price: number;
effect: string;
constructor(obj?: any) {
this.name = (obj && obj.name) ? obj.name : '';
this.price = (obj && obj.price) ? obj.price : '';
this.effect = (obj && obj.effect) ? obj.effect : '';
}
}
These could then be used in the service like this:
#Injectable()
export class ItemsService {
private items;
private _armors: BehaviorSubject<ArmorsInterface> = new BehaviorSubject(new ArmorsModel());
private _consumables: BehaviorSubject<ConsumablesInterface> = new BehaviorSubject(new ConsumablesModel());
constructor(private http: HttpClient) {
this.loadItems();
}
get getArmors() {
return this._armors.asObservable();
}
get getConsumables() {
return this._consumables.asObservable();
}
loadItems() {
this.http.get(`./assets/data/items.json`).subscribe((items: ItemsInterface) => {
this.items = items;
this._armors.next(new ArmorsModel(items));
this._consumables.next(new ConsumablesModel(items));
});
}
}
There are certainly many mistakes in the service. I am still a beginner. ;)
And in the end how you could use the service:
export class SiteHomeComponent implements OnInit {
public armors: ArmorsInterface;
constructor(private iS: ItemsService) {
}
ngOnInit() {
// Returns the Data and write it in data
this.iS.getArmors.subscribe((data) => {
this.armors = data;
});
}
}
What can be done better? Or what would you do differently? I am grateful for everything that helps me to recognize my mistakes and to learn how to do it right. Thank you for your attention. :)