0

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.

1
  • You mean something like using Object.entries() or Object.keys() or Object.values()? Look at those functions, you will probably find what you need. Commented Apr 13, 2022 at 12:48

1 Answer 1

1

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"
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.