Dave
Dave

Reputation: 93

import json file with typescript

I need to import a file with data type json with typescript. 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".

Where am I wrong? dave

Upvotes: 1

Views: 1692

Answers (1)

Don
Don

Reputation: 6882

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. The same applies to the RootObject class.

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

Upvotes: 1

Related Questions