使用typescript解析JSON文件

使用typescript解析JSON文件,json,typescript,Json,Typescript,我正在学习typescript完全是初学者,我想在网页上解析JSON数据,我也想知道这在幕后是如何工作的我确实在互联网上搜索过,但没有任何解决方案 我的代码: places.json //JSON data { "html_attributions" : [], "results" : [ { "formatted_address" : "123 Main St, Boston, MA 02110, USA", "geometry" : {

我正在学习typescript完全是初学者,我想在网页上解析JSON数据,我也想知道这在幕后是如何工作的我确实在互联网上搜索过,但没有任何解决方案
我的代码:

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"
}

如果您事先知道JSON的结构,并且希望利用typescript而不是js,那么最简单的方法就是创建适合JSON结构的接口/类型,并简单地将其转换为:

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

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

接口位置{
html_属性:数组,
结果:阵列,
状态:字符串
}
const parsedJson:Places=a;
console.log(parsedJson.status);
//嗯

JSON和获取API不是TypeScript独有的。阅读获取API:阅读JSON:这是否回答了您的问题?
interface Places {
  html_attributions: Array<any>,
  results: Array<object>,
  status: string
}

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