Home > Blockchain >  List keys and values from JSON file
List keys and values from JSON file

Time:07-22

This is my json:

{
  "USD": "United States Dollar",
  "CHF": "Swiss Franc",
  "EUR": "Euro",
  "GBP": "British Pound Sterling"
}

And this is my interface:

export interface Currencies {
  currency: string
}

I have stored the JSON into src/assets/currencies.json and now I would like to list all keys and values.

This is what I have tried:

currencies.service.ts

constructor(private _http: HttpClient) { }
  
list(): Subscription {
  return this._http.get('./assets/currencies.json').subscribe(data => data);
}

list.component.ts

getAllCurrencies(): Subscription {
  console.log(this._currencyService.list())
  return this._currencyService.list();
}

Well, this is what I get, which is not what I expect:

enter image description here

What I want is just a simple list of keys and values. E.g.

Keys:

  • USD
  • CHF
  • EUR
  • GBP

Values:

  • United States Dollar
  • Swiss Franc
  • Euro
  • British Pound Sterling

How can I do this?

CodePudding user response:

Something like this:

list(): Observable<Currencies> {
  return this._http.get('./assets/currencies.json');
}
getAllCurrencies(): Observable<Currencies> {
  return this._currencyService.list();
}
public currencies$ = this.getAllCurrencies();
<ng-container *ngIf="currencies$ | async as currencies">
  Keys:
  <ul>
    <li *ngFor="let item of currencies | keyvalue">
      {{item.key}}
    </li>
  </ul>

  Values:
  <ul>
    <li *ngFor="let item of currencies | keyvalue">
      {{item.value}}
    </li>
  </ul>
</ng-container>
  • Related