【问题标题】:Parsing JSON file using typescript使用打字稿解析 JSON 文件
【发布时间】:2020-05-23 10:11:12
【问题描述】:

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

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

【问题讨论】:

标签: json typescript


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 2017-01-22
    • 2021-09-23
    • 2017-01-28
    • 2018-09-07
    • 1970-01-01
    • 2017-05-13
    • 2018-09-07
    相关资源
    最近更新 更多