简体   繁体   English

用打字稿导入json文件

[英]import json file with typescript

I need to import a file with data type json with typescript. 我需要使用typescript导入数据类型为json的文件。 the data are: 数据是:

{
"italia": [
    {
        "regione": "Abruzzo",
        "capoluoghi": [
            {
                "citta": "Chieti",
                "sigla": "CH"
            },
            {
                "citta": "L'Aquila",
                "sigla": "AQ"
            },
            {
                "citta": "Pescara",
                "sigla": "PE"
            },
            {
                "citta": "Teramo",
                "sigla": "TE"
            }
        ]
    },{
        "regione": "Basilicata",
        "capoluoghi": [
            {
                "citta": "Matera",
                "sigla": "MT"
            },
            {
                "citta": "Potenza",
                "sigla": "PZ"
            }
        ]
    }, ...

The classes that I built are: 我建立的类是:

class Capoluoghi {
    citta: string;
    sigla: string;
  }
class Italia {
    regione: string;
    capoluoghi: Array<Capoluoghi>;
  }
class RootObject {
    italia: Array<Italia>;
  }

The function to import the data: 导入数据的功能:

function ReadRegion() {
  $.getJSON("italia.json", function (data) {
    var regionRead= new RootObject();

    var itemRead = [];
    data.italia.forEach(s => {
      itemRead = s;

      var italiaRead= new Italia();

      italiaRead["regione"] = s.regione;

      s.capoluoghi.forEach(p => {
        var capoluoghiRead= new Capoluoghi();

        capoluoghiRead["citta"] = p.citta;
        capoluoghiRead["sigla"] = p.sigla;

        italiaRead.capoluoghi.push(capoluoghiRead);
      })
      regionRead.italia.push(italiaRead);
    });  
  });
}

But unfortunately it always fails, especially when amount objects "capoluoghiRead" in "italiaRead". 但是不幸的是,它总是会失败,尤其是当“ italiaRead”中的对象数量为“ capoluoghiRead”时。

Where am I wrong? 我哪里错了? dave 戴夫

The problem is that when the classes are instantiated, the properties are not initialized, Hence when you instantiate the class Italia, the property capoluoghi is not an array. 问题在于,当实例化类时,不会初始化属性,因此,当实例化类Italia时,属性capoluoghi不是数组。 The same applies to the RootObject class. RootObject类也是如此。

  1. You will have to either manually initialize it to an empty array 您将必须手动将其初始化为空数组
  2. Or you will need to create a constructor in the class that initializes this property to an empty array ([]). 或者,您将需要在类中创建一个构造函数,以将该属性初始化为一个空数组([])。

'

class Italia {
    constructor() {
        this.capoluoghi = new Array<Capoluoghi>();
    }

    regione: string;
    capoluoghi: Array<Capoluoghi>;
}

class RootObject {
    constructor() {
        this.italia = new Array<Italia>();
    }
    italia: Array<Italia>;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM