0

I need mapping my json in Angular. I tried many codes and my own also but nothing works and I dont know why.

{
"Id":1
"Name" : "nba"
"League":{
"Id": 329
"Title": "nba"}
"Teams": { "home": {
"id":1
"Name": atlanta
....

}....etc.

It is example because I wrote it on mobile. Please help me. Thank you

I just need to mapping this json but I am not sure why it is not working

  • You need translate json to class? use this tool https://transform.tools/json-to-typescript – Den Aug 26 '23 at 11:47
  • I tried also this also by myself my own interface but nothing works – Andy Smith Hitchens Aug 27 '23 at 10:21
  • we need more info – Den Aug 27 '23 at 13:53
  • I need read json in service on ngInit and also mapping json like is above example with categories. Mockable I use for external demo http json. Angular is latest. I tried many codes from many people also mine and doesnt work and I dont understand why. I also tried from local storage but if I use local storage its gonna just read first category and another not. Can someone help with it? – Andy Smith Hitchens Aug 27 '23 at 15:48
  • can you create an example in https://codepen.io/ ? – Den Aug 28 '23 at 08:59

1 Answers1

0

Yep, sorry, this is a poorly constructed question with no details to really help anyone...

However, I'm in my helpful phase of SO usage, so here's some JSON primer stuff for you to try.

You say JSON in your code, I assume you don't really mean constructing an object like this?

const someObj = {'id': 1, 'Name':'asdf'};

And more you mean you have a .json file, presumably in your /assets directory somewhere, or even from a url, and you want to load it?

E.g. myfile.json:

{
  "Id": 1,
  "Name": "nba",
  "League": {
    "Id": 329
    "Title": "nba"
  },
  "Teams": {
    "home": {
      "id": 1,
      "Name": "atlanta"
    },
    "away": { ... }
  }
}

To read JSON directly into your classes, you can do a couple of things:

You can import the HttpClientJsonpModule into your app...

@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        FormsModule,
        HttpClientModule,
        HttpClientJsonpModule,
        ... etc

And then in your code you can read your json data from a url (here's a Google maps initialisation example):

const sub = this.httpClient.jsonp(`https://maps.googleapis.com/maps/api/js?key=${this.options.apiKey}`, 'callback')
        .subscribe(
            () => {
                this._mapReady = true;
                sub?.unsubscribe();
                this.ready();
            },
            (err) => {
                console.error('Failed to load map: ', err);
                this._mapReady = false;
                sub?.unsubscribe();
            }
        );

Or just via normal HTTP request - just request your own file. Standard GET request already tries to deserialise for you:

const sub = this.httpClient.get('/assets/data/myJsonFile.json')
    .subscribe((data: MyJsonType) => {
        sub.unsubscribe();
        console.log('Read json data as object: ', data);
    });

Or you can directly pull out from local json files in your assets (assuming you want static references and not use any kind of API requests or dynamic content):

  1. Make sure you have "resolveJsonModule": true, in your tsconfig.json file.
  2. Hit your file:
import myJsonData from '../assets/data/myJsonFile.json';

...

public get jsonData(): MyJsonDataType { return myJsonData; }

Or you have it as a string somewhere? Then you can use JSON.parse to turn it into an object...

const jsonString = `{"id":1,"Name":"asdf"...}`;

public get jsonData(): MyJsonDataType { return JSON.parse(this.jsonString); }

One thing in common, especially given then name TypeScript, is relevant typing. Note: That includes relevant capitalisation of your properties to exactly match the json keys. id !== Id.

export interface Team {
  id: number;
  name: string;
  // ...
}

export interface League {
  id: number;
  name: string;
  // ...
}

export interface GameTeams {
  home: Team;
  away: Team;
}

export interface Game {
  id: number;
  name: string;
  league: League;
  teams: GameTeams;
}

Now your stuff can read nicely, with types, from local asset json files, for example:

import gameJson from '../assets/games/123.json';

public get gameData(): Game { return gameJson; }
Krenom
  • 1,894
  • 1
  • 13
  • 20