2

I come from a Python Background and recently started programming using TypeScript and Angular2. I want to know how to obtain keys from a JSON object using TypeScript. I have a response like so:

response.text()

I pass this object to a function

removeMetaData (my_data: string){
    //(Various manipulation)...etc
}

i have read that I can call a json() method instead of text(). If I do that, what is the type I should use for my_data?

Then, If my JSON looks like this:

{
    "count": 100,
    "next_page": "http://www.test.com/users/?page=2", 
    "prev_page": "http://www.test.com/users/?page=3", 
     "results":[
     {
          "username": "johnny"
     },
     Etc....

     ]

How do I parse that? I've read I might have to use an interface but I don't understand how.

In python it's just response["next_page"] to get the key of a dictionary, then I can assign that value to a variable within the class. That is exactly what I'm trying to achieve within a component.

Thank you.

ADDITION

list() {
    this.requestService.get(this.api_path)
    .subscribe(
    response => this.populate(response.json()),
    error => this.response = error.text()
    )

}

populate(payload: object) {
    this.count = payload.count;
    this.next = payload.next;
    this.previous = payload.previous;
   *payload.results => this.users = payload.results;******
}
0

2 Answers 2

2

Declare an interface which will be used as value object.

export interface IPage
{
 count:number;
next_page:string;
prev_page:string;
results:Array<any>;
...
...
}

var my_data:IPage;

Now assign parsed json value to my_data and access all the properties with '.' operator i.e. my_data.count, my_data.results.

Feel free to throw any question.

Sign up to request clarification or add additional context in comments.

2 Comments

I like your answer, but I want to understand what I'm doing, can you tell me what is wrong with the line marked with stars?
If 'results' is available in your parsed JSON and 'users' is declared in your class then it is absolutely fine. Just keep in mind that 'users' should have right datatype to accept value from 'results'. If you are using arrow function then it should be like: (payload.results) => this.users = payload.results;
1

If I do that, what is the type I should use for my_data?

Its just a javascript object.

As an example if you json looks like:

{
  "foo": {
   "bar": "bas"
  }
}

Then in the parsed json (in variable someObj) the value someObj.foo.bar would be bas 🌹

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.