I'm going crazy.
I have this JSON:
{
'name': 'Help Me',
'filters': {
'filter1': {
'filter_id': 'wow',
'filter_query': 'maw',
},
'filter2': {
'filter_id': 'wow',
'filter_query': 'maw',
}
}
}
And i'm trying to get this in this way:
export interface MyObject {
name: string;
filters: Filters;
}
export interface Filters {
[key: string]: QueryFilter;
}
export interface QueryFilter {
filter_id: string;
filter_query: string;
friendly_filter_query: string;
}
Or in this way:
export interface MyObject {
name: string;
filters: Map<string, QueryFilter[]>;}
But in first case i got this error message:
Property 'filters' is missing in type '{ 'name': string; ...'.
And in the second case i got this:
Property 'clear' is missing in type '{ 'filter1': { 'filter_id': string; 'filter_query': string; }...'.
I really can't figure out.
Related
I created an Angular project where I'm receiving an object with the following structure from the backend:
{
status: "ok",
totalResults: 12,
articles: [
{
source: {
id: null,
name: "Sports Illustrated"
},
author: "Albert Breer",
title: "Some Title",
description: "Some description",
urlToImage: "http://google.ch/someImage.jpg"
}
]
}
I then tried to create an interface which corresponds to this object. Yet I struggled to define properties that refer to an object resp. an array of objects (e.g. article).
In my first attempt I tried to define my object inline:
export interface Noticias {
status: string;
totalResults: number;
articles: Array<{
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
}>
}
Then I tried to define the properties as duplicates:
export interface Noticias {
status: string;
totalResults: number;
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
articles: Array<{
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
}>
}
Visual Studio Code keeps showing me errors, therefore I doubt whether my approach is correct. Any help would be greatly appreciated!
Based on the json-structure on your first screenshot you'd rather create three separate interfaces: One for Noticias, one for Article and one for Source. Then Noticias contains an array of type Article and Article contains an object of type Source;
noticias.model.ts:
import { Article } from './article.model';
export interface Noticias {
status: string;
totalResults: number;
articles: Article[];
}
article.model.ts:
import { Source } from './source.model';
export interface Article {
source: Source;
author: string;
title: string;
description: string;
urlToImage: string;
}
source.model.ts:
export interface Source {
id: string;
name: string;
}
import { GraphQLString, GraphQLScalarType } from 'graphql'
import { city } from '../../Entities/Cities'
export const CREATE_CITY = {
type: Citytype,
args: {
Name: { type: GraphQLString },
CountryCode: { type: GraphQLString },
District: { type: GraphQLString },
Info: { type: GraphQLString }
},
resolve(parent: any, args: any) {
const { Name, CountryCode, District, Info } = args;
city.insert({ Name, CountryCode, District, Info });
return args;
},
}`
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
#Entity()
export class city extends BaseEntity{
#PrimaryGeneratedColumn()
Id!: number;
#Column({ type: "char", length: 35 })
Name!: string;
#Column({ type: "char", length: 3 })
CountryCode!: string;
#Column({ type: "char", length: 20 })
District!: string;
#Column({ type: "string" })
Info!: string;
}
<I'm trying to learn graphql and I'm a day in>
The Info type is suppose to be a json, in my database it looks like {"Population": 127800} with the same definition. I'm fully aware that it isn't a string/GraphQLString but I don't know how to obtain the value of this object. It returns Info: null and an error - "message": "String cannot represent value: { Population: 127800 }" for obvious reasons.
The code has the same structure as the tutorial I watched and only this video.
Link: https://www.youtube.com/watch?v=fov5e6XJgwc&ab_channel=PedroTech
Q: I want to know how to get the population ex. {"Population": 127800} when I query
it should look like Info: {"Population": 127800}
Optional: How to get the value of population if it looks like - Info: 127800
This question already has answers here:
How do I cast a JSON Object to a TypeScript class?
(28 answers)
How to parse a JSON object to a TypeScript Object
(11 answers)
How do I initialize a TypeScript Object with a JSON-Object?
(18 answers)
Closed 1 year ago.
I'm using Angular to call an external API. Json data is in format like:
[
{
"AccessGroupsIdList": [],
"FirstName": "Greg",
"LastName": "Tipton",
"LocationIdList": [],
"PermissionProfile": {
"Name": "Agent",
"PermissionProfileId": {
"ID": "xy678219-bd7c-103d-b56b-1f1234a85990"
},
"Type": 3
},
"ManagerName": "Gilchrist, George",
"Status": true,
"UserGroupID": {
"ID": "00000000-0000-0000-0000-000000000000"
},
"UserGroupName": "ROOT",
"UserId": {
"ID": "4445cc66-819a-4da0-8fbf-d0bb8ce65941"
}
}
]
How do I create a class in typescript to read it since json data is nested?
export class Employees
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile ??
ManagerName: string;
Status: boolean;
UserGroupID ??
UserGroupName : string;
UserId ??
}
Please guide if the PermissionProfile, PermissionProfile will be separate nested classes?
How do I declare those?
To extend Andrew Halil's answer, I would use interfaces instead of classes in your definitions, since there do not appear to be any class methods involved; you are just describing the shape of a JSON object returned from a server
export interface Employee
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile: PermissionProfile;
ManagerName: string;
Status: boolean;
UserGroupId: ID;
UserGroupName : string;
UserId: ID;
}
export interface PermissionProfile
{
name: string;
permissionProfileId: ID;
type: string;
}
export interface ID
{
id: string;
}
Now as for an implementation, I don't use Angular all that much but you would do something like this to get the items typed
async function listEmployees(): Promise<Employee[]> {
// Make a fetch call to the API endpoint
const data = await fetch('https://some-api-endpoint.web/employees')
// if the response comes back ok, return the JSON-ified response.
.then(res => {
if(res.ok) return res.json()
return [];
});
// Instruct typescript that "data" is to be treated as an array of Employee elements.
return data as Employee[]
}
Try declaring the Typescript class structures as follows:
export class Employees
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile: PermissionProfile;
ManagerName: string;
Status: boolean;
UserGroupId: UserGroupID;
UserGroupName : string;
UserId: UserID;
}
export class PermissionProfile
{
name: string;
permissionProfileId: PermissionProfileID;
type: string;
}
export class PermissionProfileID
{
id: string;
}
export class UserGroupID
{
id: string;
}
export class UserID
{
id: string;
}
I would suggest to name the property names consistently with an Id (e.g. with UserGroupId). The name and type class property names are valid in TypeScript (unlike with the C# syntax).
I'm trying to build a Azure cognitive text translator app in angular. Initially I need to load the supported languages. But when I use this link https://api.cognitive.microsofttranslator.com/languages?api-version=3.0. I'm getting response like this
"translation": {
"af": {
"name": "Afrikaans",
"nativeName": "Afrikaans",
"dir": "ltr"
},
"ar": {
"name": "Arabic",
"nativeName": "العربية",
"dir": "rtl"
},
"bg": {
"name": "Bulgarian",
"nativeName": "Български",
"dir": "ltr"
},
...
}
How to create a model that holds this type of json?
When I tried json2ts.com for building the model, it creates object for each language like
export interface Af {
name: string;
nativeName: string;
dir: string;
}
export interface Ar {
name: string;
nativeName: string;
dir: string;
}
export interface Bg {
name: string;
nativeName: string;
dir: string;
}
export interface Translation {
af: Af;
ar: Ar;
bg: Bg;
}
Do I need to create interface for all the available languages?
are there any other simple way to handle this?
The translation property of that object is a key-value map.
You could model the whole thing as follows:
type Dir = "ltr" | "rtl";
interface Translation {
name:string;
nativeName:string;
dir: Dir;
}
interface LangResponse {
translation: {[langCode:string]: Translation};
}
You could define a Typescript interface modeling the JSON data.
export interface LanguageInfo {
name: string
nativeName: string
dir: string
code?: string
toScripts?: Array<LanguageInfo>
}
export interface TranslationLanguages {
langCode: string
info: LanguageInfo
}
function fromJSON(json_data: string | Object): TranslationLanguages {
let obj: TranslationLanguages;
if (typeof json_data === "object") {
obj = json_data as TranslationLanguages;
} else {
obj = JSON.parse(json_data);
}
return obj;
}
I am trying to consume a web API that returns the following data
{
"FileStatuses": {
"FileStatus": [
{
"accessTime": 0,
"blockSize": 0,
"childrenNum": 13,
"fileId": 16396,
"group": "supergroup",
"length": 0,
"modificationTime": 1553247533630,
"owner": "hduser",
"pathSuffix": "demo-data",
"permission": "755",
"replication": 0,
"storagePolicy": 0,
"type": "DIRECTORY"
},
{
"accessTime": 0,
"blockSize": 0,
"childrenNum": 7,
"fileId": 16410,
"group": "supergroup",
"length": 0,
"modificationTime": 1550659883380,
"owner": "hduser",
"pathSuffix": "instacart",
"permission": "755",
"replication": 0,
"storagePolicy": 0,
"type": "DIRECTORY"
}
]
}
}
I created a service like this and the class to parse the json response to it:
public getHadoopDirList(): Observable<FileStatus[]> {
return this.http.get<FileStatus[]>(this.webHdfsUrl, {}).pipe(map(data => data));
}
export class FileStatus {
accessTime: number;
blockSize: number;
childNum: number;
fileId: number;
group: string;
length: number;
modificationTime: number;
owner: string;
pathSuffix: string;
permission: string;
replication: number;
storagePolicy: number;
type: string;
}
i subscribed to it on the component but when i try to iterate over it on the template i get the following ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
I think the problem is the way how to map it but I didn't know how to solve it
use http://json2ts.com/ to convert JSON to interface
Your inteface should be like below
export interface FileStatus {
accessTime: number;
blockSize: number;
childrenNum: number;
fileId: number;
group: string;
length: number;
modificationTime: any;
owner: string;
pathSuffix: string;
permission: string;
replication: number;
storagePolicy: number;
type: string;
}
export interface FileStatuses {
FileStatus: FileStatus[];
}
export interface FileStatusesRootObject {
FileStatuses: FileStatuses;
}
and then
return this.http.get<FileStatusesRootObject>(
You need to make sure the data types match. It expects a result of type FileStatus[]. Thus, on your RxJS's map(), you will need to return the right data respectively by selecting FileStatus, which contains the array of objects with the type of FileStatus
public getHadoopDirList(): Observable<FileStatus[]> {
return this.http.get<FileStatus[]>(this.webHdfsUrl, {})
.pipe(
map(data => data['FileStatuses']['FileStatus'])
);
}