JSON object interfaced return undefined - json

i want to create a pipe in Angular 9 that translate my table words in various language.
I have created a JSON file that contains a key and the value for a translation service. I have also created some interfaces for this json file.
translate.json
{
"lang":[
{
"IT": [
{ "name": "Nome" },
{ "surname": "Cognome" },
{ "email": "E-mail" },
{ "cf": "Codice fiscale" },
{ "phone": "Cellulare" },
{ "age": "Età" },
{ "city": "Città" },
{ "job": "Lavoro" }
]
},
{
"EN": [
{ "name": "first name" },
{ "surname": "last name" },
{ "email": "E-mail" },
{ "cf": "Fiscal code" },
{ "phone": "Phone" },
{ "age": "Age" },
{ "city": "City" },
{ "job": "Job" }
]
}
]
}
translateInterface.ts
export interface Lang {
lang: (Langs)[];
}
export interface Langs {
IT: (ITEntityOrENEntity)[];
EN: (ITEntityOrENEntity)[];
}
export interface ITEntityOrENEntity {
name: string;
surname: string;
email: string;
cf: string;
phone: string;
age: string;
city: string;
job: string;
}
translate.service.ts
translate(key: string, lang:string) {
return this.http.get<Langs>('assets/json/translate.json').subscribe((res: Lang) => console.log(res))
}
I have updated the json and the interface, now how i can return one object of the IT array?

I see multiple issues.
You don't need to define the properties IT and EN as arrays in the JSON file. It could very well be plain JS objects.
{
"IT": {
"name": "Nome",
"surname": "Cognome",
"email": "E-mail",
"cf": "Codice fiscale",
"phone": "Cellulare",
"age": "Età",
"city": "Città",
"job": "Lavoro"
},
"EN": {
"name": "first name",
"surname": "last name",
"email": "E-mail",
"cf": "Fiscal code",
"phone": "Phone",
"age": "Age",
"city": "City",
"job": "Job"
}
}
There is no need for two different interfaces. You could assign one single interface.
export interface Details {
name: string;
surname: string;
email: string;
cf: string;
phone: string;
age: string;
city: string;
job: string;
}
You are defining the type as array in Langs interface instead of the defined details interface. You could do something like
export interface Langs {
IT: Details;
EN: Details;
}
At the moment you're wrongfully returning the subscription instead of the observable from the function. You could return the observable from the service and subscribe to it the component controller.
Service
translate(language: string): Observable<Details> {
return this.http.get<Langs>('assets/json/translate.json').pipe(
map(response => response[language])
);
}
Component
ngOnInit() {
this.translateService.translate('IT').subscribe(
details => { this.details = details },
error => { }
);
}
Template
<span>{{ details?.name }}</span>
<span>{{ details?.surname }}</span>
<span>{{ details?.email }}</span>
...
Working example: Stackblitz

Related

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 };
}

How to map an object from JSON file to another object?

Here is my json file
{
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": m,
"data": { "age": 26, "born": "UK" }
},
]
}
This data array could have more entries.
I have to map the values into an interface which looks like:
InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
I am unable to change the interface. So I'm trying to do some pseudo coding.
const list;
list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
return {
id: value.id,
title: if(value.gender === "m")? "Mr" : "Mrs",
firstName: value.firstName,
lastName: value.lastName,
age: value.data.age,
//...
}
}
I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.
// Copied in the JSON for demonstration
const sourceJson = {
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": "m",
"data": { "age": 26, "born": "UK" }
},
]
};
// Declared the InterfacePerson interface
interface InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
return {
id: value.id,
// Removed the `if` statement due to ternary conditional
title: ((value.gender === "m") ? "Mr" : "Mrs"),
firstName: value.firstName,
lastName: value.lastName,
// Wrapped the value.data.age in a string conversion
age: String(value.data.age),
location: value.data.born
};
}
// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);
// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));
And for a live example, check out this TypeScript Playground script containing this solution.

Converting json object to typescript interface causing error in the mock object while unit testing in Angular 11

I am receiving a json response in an Angular 11 app and I have created an interface corresponding to that json object. The json object is
{
"division": {
"uid": "f5a10d90-60d6-4937-b917-1d809bd180b4",
"name": "Sales Division",
"title": "Sales",
"type": "Form",
"formFields": [
{
"id": 1,
"name": "firstName",
"label": "First Name",
"value": "John"
},
{
"id": 2,
"name": "lastName",
"label": "Last Name",
"value": "Smith"
}
]
}
}
The typescript interface I created for this json object is
export interface FormField {
id: number;
name: string;
label: string;
value: string;
}
export interface Division {
uid: string;
name: string;
title: string;
type: string;
formFields: FormField[];
}
export interface Division {
division: Division;
}
I am using a service division.sevice.ts to fetch the above json response from API and everything works fine. I am trying to write unit tests for the this service in the division.service.spec.ts file. I created a mockDivisionObj inside this file for testing purpose which is shown below.
mockDivisionObj = {
"division": {
"uid": "f5a10d90-60d6-4937-b917-1d809bd180b4",
"name": "Sales Division",
"title": "Sales",
"type": "Form",
"formFields": [
{
"id": 1,
"name": "firstName",
"label": "First Name",
"value": "John"
},
{
"id": 2,
"name": "lastName",
"label": "Last Name",
"value": "Smith"
}
]
}
}
An error is shown which says
Property 'division' is missing in type '{ uid: string; name: string; title: string; type:
string; formFields: { id: number; name: string; label: string; value: string; }[]; }' but
required in type 'Division'.
I think the way I created the interface may be wrong but I couldn't figure out what exactly is causing the issue. Please help me out with this.
I was able to fix the issue by changing the name of one of the interfaces in the file to 'AppDivision' as shown below.
export interface FormField {
id: number;
name: string;
label: string;
value: string;
}
export interface Division {
uid: string;
name: string;
title: string;
type: string;
formFields: FormField[];
}
export interface AppDivision {
division: Division;
}
The same name for two interfaces caused the error in the unit test mock object.
Your code is fine.To solve this error you can try the code below =>
this.division = this.mockDivisionObj.division as Division;
Check the Link: StackBlitz Demo link.

Elasticsearch: how to store all json objects dynamically

I'm trying to store all Json objects through elasticsearch.
client.create({
index: 'index',
type: 'type',
id:"1"
body:result[0]
},function (error,response)
{
if (error)
{
console.log('elasticsearch cluster is down!');
}
else
{
console.log('All is well');
}
});
In this result[0] I'm getting my first value of a Json object but I need to store all Json objects dynamically.
The output which i'm getting is:
-> POST http://localhost:9200/index/type/1?op_type=create
{
"Name": "Martin",
"Age": "43",
"Address": "trichy"
}
<- 201
{
"_index": "index",
"_type": "type",
"_id": "1",
"_version": 4,
"created": true
}
But I need an output like this:
-> POST http://localhost:9200/index/type/1?op_type=create
{
"Name": "Martin",
"Age": "43",
"Address": "trichy"
},
{
"Name": "vel",
"Age": "23",
"Address": "chennai"
},
{
"Name": "ajay",
"Age": "23",
"Address": "chennai"
}
<- 201
{
"_index": "index",
"_type": "type",
"_id": "1",
"_version": 4,
"created": true
}
What you need is to use the bulk endpoint in order to send many documents at the same time.
The body contains two rows per document, the first row contains the index, type and id of the document and the document itself is in the next row. Rinse and repeat for each document.
client.bulk({
body: [
// action description
{ index: { _index: 'index', _type: 'type', _id: 1 } },
// the document to index
{ Name: 'Martin', Age: 43, Address: 'trichy' },
{ index: { _index: 'index', _type: 'type', _id: 2 } },
{ Name: 'vel', Age: 23, Address: 'chennai' },
{ index: { _index: 'index', _type: 'type', _id: 3 } },
{ Name: 'ajay', Age: 23, Address: 'chennai' }
]
}, function (err, resp) {
// ...
});
I suspect your result array is the JSON you get from your other question from yesterday. If so, then you can build the bulk body dynamically, like this:
var body = [];
result.forEach(function(row, id) {
body.push({ index: { _index: 'index', _type: 'type', _id: (id+1) } });
body.push(row);
});
Then you can use the body in your bulk call like this:
client.bulk({
body: body
}, function (err, resp) {
// ...
});

Populating Class[] with JSON in TypeScript

As part of my model I have this class in TypeScript:
module App.Model {
export class Unit {
id: number;
participantId: number;
name: string;
isProp: boolean;
}
}
In the controller, I need a a hash with the id as key:
module App.Controllers {
export class MyController {
public units: App.Model.Unit[];
populateDemoData() {
this.units = {
"1": { "id": 1, "participantId": 1, "name": "Testname", "isProp": true },
"2": { "id": 2, "participantId": 1, "name": "Another name", "isProp": false }
};
}
}
}
However, compiling the controller, I get the following error message:
Error 2 Cannot convert '{ }; [n: number]: App.Model.Unit; }' to ' }; [n: number]: App.Model.Unit; }' is missing property 'concat' from type 'App.Model.Unit[]'.
What am I doing wrong? And why is TypeScript asking for a concat property?
You defined units as an Array object, but assigned it a literal object. Just to clarify, a hash (a literal object) is not an array.
If all the IDs are an integer you can still use the array but it would be like this instead:
populateDemoData() {
this.units = [];
this.units[1] = { "id": 1, "participantId": 1, "name": "Testname", "isProp": true };
this.units[2] = { "id": 2, "participantId": 1, "name": "Another name", "isProp": false };
}
Edit:
Ok, you have to define a hash table to do that, but you also need to make App.Model.Unit an interface that matches your JSON objects.
module App.Model {
export interface Unit {
id: number;
participantId: number;
name: string;
isProp: boolean;
}
export interface UnitHashTable {
[id: string]: Unit;
}
}
module App.Controllers {
export class MyController {
public units: App.Model.UnitHashTable;
populateDemoData() {
this.units = {
"1": { "id": 1, "participantId": 1, "name": "Testname", "isProp": true },
"2": { "id": 2, "participantId": 1, "name": "Another name", "isProp": false }
};
}
}
}