Parsing JSON items using Angular - json

I have a JSON object and I want to give the values of the properties to 4 of my variables using Angular, which are the following:
authorText : string;
titleText : string;
durationText : string;
genreText : string;
And here is the JSON:
"{"n":{
"_id":1101,
"labels":[
"Song"
],
"properties":{
"duration":"214000",
"author":"Shawn Mendes",
"genre":"pop",
"title":"In My Blood"
}
}
}"
I tried using this and similar solutions to this:
Object.keys(editData).forEach(function (key) {
console.log(key);
if(key === "author"){
this.authorText = editData[key];
}
console.log( key , editData[key] );
});
But the key is always 0 for some reason.
EDIT
Added the image of the JSON:
The string I printed before was done as following : Saving it as global variable and then using JSON.stringify(temp1);.

You can use this:
const { duration, author, genre, title } = this.editData[0].n.properties;
this.song = {
authorText: author,
titleText: title,
durationText: duration,
genreText: genre
};
Here, we're destructuring the properties from the properties key and just assigning them to the song Object's keys one by one.
A better thing to do would be just to name the fields as duration, author, genre, and title. Then you can simply do something like this:
export interface Song {
author: string;
title: string;
duration: string;
genre: string;
}
And in your function:
this.song = { ...editData[0].n.properties };
Here, we're using the spread operator(...) to spread the properties object's keys and assign them to the song property on your Component Class.
Here's a Sample StackBlitz for your ref.

You can just do this:
this.song = this.editData.n.properties;
I have a stackblitz demonstrating it here: https://stackblitz.com/edit/angular-udmdqr
The basic code is here:
import { Component, Input } from '#angular/core';
#Component({
selector: 'hello',
template: `<h1>Hello {{song.author}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
song: Song;
editData = {
"n": {
"_id": 1101,
"labels": [
"Song"
],
"properties": {
"duration": "214000",
"author": "Shawn Mendes",
"genre": "pop",
"title": "In My Blood"
}
}
}
constructor() {
this.song = this.editData.n.properties;
}
}
export interface Song {
duration: string;
author: string;
genre: string;
title: string
}

Related

angular ngx-treeview from Json object error : A text of item must be string object

this treeview item text is confusing me for the past week
this is how I load the items into the tree view:
ngOnInit(): void {
this.items = this.getItems([JSON.stringify(this.json_obj)]);
}
getItems(parentChildObj: any[]) {
let itemsArray: TreeviewItem[] = [];
parentChildObj.forEach((set: TreeItem) => {
itemsArray.push(new TreeviewItem(set,true))
});
return itemsArray;
}
and this is how I create the nested Json object from non-nested Json file :
this.departments.forEach(element => {
if(element.ParentID == 0){
p_counter++;
this.json_obj.push(
{
text: element.DepartmentName ,
value: 'p'+p_counter.toString() ,
children: [],
id: element.DepartmentID.toString() ,
} as never
);
element.DepartmentName = 'fixed';
}
});
the template is simple as that:
<ngx-treeview [items]="items" dir ="rtl"></ngx-treeview>
btw- it creates a perfect nesting but it cant read the object properties in
new TreeviewItem(set,true);
because it's undefined.
Error : A text of item must be string object at new TreeviewItem
please help me figure this out, what can I do to make it work?
You have used
text: element.DepartmentName ,
value: 'p'+p_counter.toString() ,
children: [],
id: element.DepartmentID.toString()
It seems you have not followed TreeItem interface given in treeview-item.d.ts
export interface TreeItem {
text: string;
value: any;
disabled?: boolean;
checked?: boolean;
collapsed?: boolean;
children?: TreeItem[];
}
you should remove id because that is not property of TreeItem interface.
import { Component,OnInit } from '#angular/core';
import { TreeviewItem } from 'ngx-treeview';
#Component({
selector: 'my-app',
template: `<ngx-treeview [items]="items"></ngx-treeview>`
})
export class AppComponent implements OnInit {
items: TreeviewItem[];
ngOnInit() {
this.items = this.getItems();
}
getItems(){
// fetch api response
// convert response into this format (object can be nested, should contain below keys only with given type)
// {
// text: string;
// value: any;
// disabled ?: boolean;
// checked ?: boolean;
// collapsed ?: boolean;
// children ?: TreeItem[];
// }
const item = new TreeviewItem({
text: 'Children', value: 1, children: [
{ text: 'Baby 3-5', value: 11 },
{ text: 'Baby 6-8', value: 12 },
{ text: 'Baby 9-12', value: 13 }
]
});
return [ item ];
}
}
stackblitz example

how to create a list of object using json in Angular?

Hi I'd like to create a small authentication service in my angular application, I have a JSON file containing the information about my users:
{
"Users": [
{
"type":"teacher",
"id":0,
"name":"TEACHER ONE",
"login":"tone",
"password":"d450c5dbcc10db0749277efc32f15f9f"
},
{
"type":"student",
"id":1,
"name":"STUDENT ONE",
"login":"sone",
"password":"ec80dcc5a3eab73a4f128b66c1e4b92a"
},
{
"type":"student",
"id":2,
"name":"STUDENT TWO",
"login":"stwo",
"password":"62e73bf0deb1871860702b064106f1dc"
}
]
}
and here's what I try for my authentifiaction
import { Injectable } from '#angular/core';
import * as users from '../assets/Users.json';
import { clientType } from "./clientType";
#Injectable({
providedIn: 'root'
})
class user {
$type: clientType; //I put a dollar so equals won't compare this property
$id: number; //I put a dollar so equals won't compare this property
$name: string; //I put a dollar so equals won't compare this property
login: string;
password: string;
constructor(type: clientType, id: number, name: string, login: string, password: string) {
this.$type = type;
this.$id = id;
this.$name = name;
this.login = login;
this.password = password;
}
}
export class AuthService {
private userList: /*don't know what to put*/ = /*don't know what to put*/;
constructor() { }
consultData( ): void{
}
returnUsers() {
return this.userList;
}
}
I'm trying to get an array of users using my JSON file but I don't know how to extract the JSON object as user objects, can someone help me finding how ?

How to set json file to object's array in Angular

how to set json file to my "Client" object's array?
I have json, which looks like this:
Clients.json
{
"clients": [
{
"firstName": "nameA",
"lastName": "lastA",
"doctorsName": "domm",
"procedure": "consultation",
"registrationDate": "new Date(2019, 10, 12)",
"isAlreadyServed": "false"
},
{
"firstName": "nameB",
"lastName": "lastB",
"doctorsName": "domm",
"procedure": "procedureA",
"registrationDate": "new Date(2019, 10, 12)",
"isAlreadyServed": "false"
},
{
"firstName": "nameC",
"lastName": "lastC",
"doctorsName": "doctorA",
"procedure": "procedureC",
"registrationDate": "new Date(2019, 10, 12)",
"isAlreadyServed": "false"
},
...
...
...
And how can I set it to object's array Client.service.ts
clients: Client[] = this.http.get('path.Clients.json') // ??
Since your data is in the client-side as a JSON file. Though you can use HttpClient, here is another solution for the same.
You can directly import the JSON as a constant and assign it to clients as of TS 2.9 (docs).
import Clients from 'path/to/client/json';
clients: ClientsJson = Clients;
where the ClientsJson interface would look like this.
export interface ClientsJson {
clients: Client[];
}
export interface Client {
firstName: string;
lastName: string;
doctorsName: string;
procedure: string;
registrationDate: Date;
isAlreadyServed: boolean;
}
Here is a working example on StackBlitz.
You first need to define an interface that matches your object structure:
public interface ClientConfiguration {
firstName: string;
lastName: string;
doctorsName: string;
// And so on...
}
Then, just like the code you have shown, you need to type the http.get method in order to obtain the correct output.
public getConfiguration(): Observable<Array<ClientConfiguration>> {
return this.http.get<Array<ClientConfiguration>>('path/to/client/json');
}
Since my getConfiguration() method returns an observable, you will need to subscribe to it in your components or services:
#Component({ ... })
export class MyComponent implements OnInit {
public ngOnInit(): void {
this.getConfiguration().subscribe(result: Array<ClientConfiguration> => {
this.clientConfiguration = result;
});
}
public getConfiguration(): Observable<Array<ClientConfiguration>> {
return this.http.get<Array<ClientConfiguration>>('path/to/client/json');
}
}
You can read more here about HttpClient at Angular's official documentation: https://angular.io/guide/http
Hope it helps.

Angular 5 consume json consisting of one object [duplicate]

This question already has answers here:
Angular 5+ cannot save result form observable response
(4 answers)
Closed 4 years ago.
I am working on a barcode scanning app with angular.
The number of the barcode returns a json containing a "box" object. How can i parse the box json to a box class in angular?
This is my existing code:
//Injectable Dataservice
export class BoxService {
//url vars
urlBegin:string = "url";
urlEinde:string = "/last-order";
url:string;
test;
constructor(#Inject(HttpClient) private http: HttpClient){
}
getBox(barcode):Observable<Box>{
this.url = this.urlBegin + barcode + this.urlEinde;
return this.http.get<Box>(this.url);
}
}
// My component using the service showBox() is the method using the service
import { Component, OnInit, Inject, Injectable } from '#angular/core';
import { BoxService } from '../BoxService';
import { Box } from '../Box';
#Component({
selector: 'app-Data',
templateUrl: './Data.component.html',
styleUrls: ['./Data.component.css']
})
export class DataComponent implements OnInit {
uitkomst:String;
box:Box;
constructor(private boxService:BoxService) { }
zoekBarcode(barcode):void{
this.uitkomst = "ik heb info over deze barcode: " + barcode;
this.showBox(barcode);
}
showBox(barcode){
this.boxService.getBox(barcode).subscribe(data => this.box = data);
console.log(this.box.boxNumber.toString());
}
ngOnInit() {
}
}
// Box Class
import { Contentline } from "./Contentline";
export class Box {
boxNumber: number;
status: number;
shipTo: string;
shipToName: string;
contentLines: Contentline[];
}
//Contentline class
export class Contentline {
articleIdCustomer: string;
description: string;
orderId: string;
orderLineId: string;
quantity: number;
uom: string;
closet: any;
shelf: any;
deliveryDate: string;
}
My JSON string looks like this:
{
"boxNumber": 13100973,
"contentLines": [
{
"articleIdCustomer": "112050",
"description": " Nutraclear naaldvrije connector",
"departmentName": null,
"deliveryDate": "2018-06-26T22:00:00Z"
},
{
"articleIdCustomer": "101512",
"description": " LIJN INFUUSVERLENG 400CM 1,5 MM PE/PVC",
"departmentName": null,
"deliveryDate": "2018-06-27T22:00:00Z"
},
{
"articleIdCustomer": "101053",
"description": " LIJN INFUUS 700CM 1X2,1MM 25ST",
"departmentName": null,
"deliveryDate": "2018-06-27T22:00:00Z"
},
{
"articleIdCustomer": "101053",
"description": " LIJN INFUUS 700CM 1X2,1MM 25ST",
"departmentName": null,
"deliveryDate": "2018-07-03T22:00:00Z"
},
{
"articleIdCustomer": "101053",
"description": " LIJN INFUUS 700CM 1X2,1MM 25ST",
"departmentName": null,
"deliveryDate": "2018-07-04T22:00:00Z"
},
{
"articleIdCustomer": "101386",
"description": " DOP AFSLUIT ENTERALE SPUIT ENFIT (PER 8",
"departmentName": null,
"deliveryDate": "2018-06-25T22:00:00Z"
}
],
"status": 3,
"otherDepartments": []
}
If you are interested in typesafe object creation consider following Box class constructor (I simplified it to single field):
interface iBox { /* You will get this structure from HTTP get */
articleIdCustomer: string,
}
class Box implements iBox {
articleIdCustomer: string,
constructor(iBox: IBox) {
this.articleIdCustomer =
(typeof(iBox.articleIdCustomer) !== 'undefined') ? iBox.articleIdCustomer : undefuned
}
}
and then at recieving JSON object from web:
this.boxService.getBox(barcode).subscribe((data: iBox) => this.box = new Box(data));
If some of fiels are mandatory, you can throw Errors in constructor
Rewrite you below the line of code
this.boxService.getBox(barcode).subscribe(data => this.box = data);
as
this.boxService.getBox(barcode).subscribe(data:Box => this.box = data);
you can give type to data it automatically cast all your object accordingly.

fail reading object type of json

i have an Object type of json that I cant read...
this is my json:
body: {
"111": {
"name": "name1",
"status": 10000
},
"222": {
"name": "name2",
"status": 20000
},
"333": {
"name": "name3",
"status": 30000
}
}
and I want to know how to present it in my html?
this is my attempt:
<md-content>
<h1 align="center">{{title}}</h1>
<h2>list of items:</h2>
<div class="list-bg" *ngFor="#item of items | async">
ID: {{item.name}} <p></p> Number of Items: {{item.status}}
</div>
</md-content>
not only that it dosent work, im trying to figure out how to read each line the object id's(those: 111, 222, 333)
this is my model:
export interface MyModel {
name: string;
status: number;
}
this is my component:
export class MyCmp implements OnInit {
retJson: Observable<MyModel[]>
constructor(private _myService: MyService) {};
public showData(): void {
this.retJson = this._myService.getData();
}
}
thanks!
You haven't included how you load your json, so I'll write a more general example:
interface MyModel {
name: string;
status: number;
}
interface MyResponse {
body: { [id: string]: MyModel }
}
let response: MyResponse = JSON.parse(RESPONSE_STRING);
Object.keys(response.body).forEach(id => {
let model = response.body[id];
console.log(`id: ${ id }, name: ${ model.name }, status: ${ model.status }`);
});
What's missing here is the RESPONSE_STRING, which I'm not sure how you get.
As for the template, I'm not an angular developer but as far as I understand ngFor is used for arrays, and you don't have an array in your json structure.
ngFor loop only will work for array. Your body json is key value object, so it wouldn't work.
If you want to make it work, it's either:
you use an additional pipe to convert key value object to array using pipe, solution discussed here: Iterate over TypeScript Dictionary in Angular 2, then you can use
*ngFor="let item of items | async | mapToIterable"
Or process it in your ts file, instead of
this.retJson = this._myService.getData();, use this._myService.getData().subscribe(x => this.retJson = processToArray(x))