user6509972 user6509972 - 1 month ago 11
JSON Question

Accessing Json data in typescript

I have a JSON object from the Facebook api that has all the posts from a public page. I am using type script to grab the object and assign it to a variable. But I can't figure out how to access the fields. How do you access JSON data in type script?

Here is my JSON file:
https://graph.facebook.com/1650393515218783?fields=posts&access_token=EAAN3TCkzCxsBACdSQIu3KDiORivp0eEeQWNMBu1aT8TnEWYEqQhblcl4IZAykwIwDFF5v6LB8BYNyOXYWrRhE7ildN2lnXFqwpnv7Bzq3Kh2ZB5FZBAMxrbpNEX2znds1G86AurOZAD0R1W3ec1ZBhwr8LNZAZCyGjgtMGbiZA44XwZDZD

Here is my function:

getBadger() {

var link = 'https://graph.facebook.com/1650393515218783? fields=posts&access_token=EAAN3TCkzCxsBACdSQIu3KDiORivp0eEeQWNMBu1aT8TnEWYEqQhblcl4IZA$

this.http.get(link).subscribe(data => { this.data = data; this.posts = JSON.parse(data._body); });

Answer

this.posts.data[0].message will give you the message of the first story in the response you got back.

But you probably want to model the response using types other than any, in which case you can define the following:

interface FbApiResponse {
    posts: {
        id: string;
        data: FBResponseElement;
    }
}

interface FbResponseElement {
    message?: string;
    story?: string;
    created_time: string;
    id: string;
}

Though, I'm guessing this based on your data. I don't actually know what the API you're working with is, what its responses look like, or what they should be named.

You could then use a type assertion on your call to JSON.parse:

JSON.parse(data._body) as FbApiResponse