user6509972 user6509972 - 5 months ago 39
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:

Here is my function:

getBadger() {

var link = ' fields=posts&access_token=EAAN3TCkzCxsBACdSQIu3KDiORivp0eEeQWNMBu1aT8TnEWYEqQhblcl4IZA$

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

Answer[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