Home > Mobile >  Access JSON fields (Angular - TypeScript)
Access JSON fields (Angular - TypeScript)

Time:04-13

I have a small Angular application that sends a request to an API and gets a JSON object in return.
I want to write the results to a text field, but don't want it to "look like" a JSON. Structure of the JSON:

{
  "Jane": 3,
  "Tim": 5,
  ...
}

The length and keys (names) depend on the request to the API. I access the API like this:

this.http.post(url, inputData, { headers: headers, responseType: 'text' }).subscribe(data => this.updateTextField(data));

updateTextField function:

  updateTextField(result: string) {

    var json = JSON.parse(result);
    
    this.outputTextField.nativeElement.value = this.outputTextField.nativeElement.value   this.inputTextField.nativeElement.value   "\n"   JSON.stringify(json)   "\n"
  }

I just can't figure out how I can access the fields in the JSON object...
Once I can access the fields I could write a formatting function to create the output string in whatever format I want.

The idea would be to print the entries of the JSON sorted alphabetically by name and add some extra description.

Any pointers on how I could achieve it.

CodePudding user response:

You can simply take the keys from the JSON object provided that there is one JSON object in the response as you have shown in the question. Sort the keys in ascending order and create a function to map the values based on sorted keys.

  updateTextField(result: string) {


    const resultJson = JSON.parse(result);
    //keys now sorted alphabetically 
    const keys = Object.keys(resultJson).sort((a, b) => a.localeCompare(b));
    
   // do things with the keys using loop 

   for (const key of keys) console.log(resultJson[key]);

   this.outputTextField.nativeElement.value = this.outputTextField.nativeElement.value   this.inputTextField.nativeElement.value   "\n"   JSON.stringify(json)   "\n"
  }
  • Related