-1

I am learning typescript totally beginner and I wanna parse JSON data on a web page also I want to know how this works behind the scenes I did search over the internet but didn't any solution
my code:

var a = fetch("places.json")
  .then(response => response.json())
  .then(json => console.log("json"));
//this is printing json data on console

places.json


//JSON data
{
  "html_attributions" : [],
  "results" : [
     {
        "formatted_address" : "123 Main St, Boston, MA 02110, USA",
        "geometry" : {
           "location" : {
              "lat" : 42.3744875,
              "lng" : -71.06347439999999
           },
           "viewport" : {
              "northeast" : {
                 "lat" : 42.37581182989273,
                 "lng" : -71.06218627010728
              },
              "southwest" : {
                 "lat" : 42.37311217010728,
                 "lng" : -71.06488592989272
              }
           }
        },
        "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
        "id" : "4747c342bc144e98fba53bf2f41b6ed707e2fef0",
        "name" : "123 Main St",
        "place_id" : "ChIJd_ueCe1w44kRD_KFuN5w5nA",
        "plus_code" : {
           "compound_code" : "9WFP+QJ Boston, Massachusetts, United States",
           "global_code" : "87JC9WFP+QJ"
        },
        "reference" : "ChIJd_ueCe1w44kRD_KFuN5w5nA",
        "types" : [ "street_address" ]
     }
  ],
  "status" : "OK"
}

1 Answers1

1

If you know the structure of the JSON beforehand and you want to leverage typescript over js - then the easiest way would be to create interface/type that fits JSON structure and simply cast it like:

interface Places {
  html_attributions: Array<any>,
  results: Array<object>,
  status: string
}

const parsedJson: Places = <Places>a;
console.log(parsedJson.status);
// OK

Sonac
  • 58
  • 1
  • 7