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):
- Make sure you have
"resolveJsonModule": true,
in your tsconfig.json
file.
- 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 Type
Script, 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; }