1

I'm having problems to import JSON data into my angular application.

What I'm doing:

  1. Import the json file into a variable:

import _datos from '../../../assets/data.json';

  1. As specified in the answers of this question (How to import JSON File into a TypeScript file?), I'm using the typing.d.ts file in order to be able to read the information.

  2. Declaring an interface in order to improve the readability of the code:

export interface Datos{
  property1: String,
  property2: String,
  etc.
}
  1. Declaring and instantiating the array with the json file imported:
datos: Datos[] = _datos;

What is expected

The variable "datos" should have the content of the JSON file as an array.

What actually happens

Type '{}' is missing the following properties from type 'Datos[]': length, pop, push, concat, and 26 more.ts(2740).

Further information

I've done it before with a smaller JSON file (this one has about 26 properties each object and +100k elements) and worked fine. However, this one is failing and I don't really know why.

  • 2
    Let me guess (you didn't provide a [mre] so I have to...): you didn't provide the generic type to the HTTP client? – jonrsharpe Oct 08 '21 at 18:14
  • I'm sorry about it! I'm not very familiar with the use of stackoverflow, I'll edit the question asap. However, I'm not using HTTP at all. It's a local json that needs to be read in the local angular server. I'll provide more info in the question! –  Oct 11 '21 at 15:00

2 Answers2

0

Okay it was a very simple mistake:

One of the 26 properties in the JSON file was not written properly. In order for this to work, it is needed that the properties in the JSON file and the properties in the interface match.

The JSON file is something like this:

[
    {
        "organo_de_contratacion": "Consorcio de Transportes de la Bahía de Cádiz",
        "estado_de_la_licitacion**:**": "Resuelta",
        ...

So that the : slipped before the ending of the property and missmatched the interface property.

-1

To avoid the error:

Type '{}' is missing the following properties from type ...

Ensure that the object _datos is being assigned is an array of objects of type Datos.

This occurs when assigning an object { .. } to an array of objects [ {}, .. ]

Your variable that holds the imported array needs to be declared as follows:

_datos: Datos[] = [];

Then import your JSON file data into _datos.

I would suggest debugging the value of _datos before it is assigned to the datos variable.

Andrew Halil
  • 1,195
  • 15
  • 15
  • 21
  • As I mentioned in the question, I've tried this before with other json files and it worked just fine, so I don't think that the problem is the assignment. I'm not sure what is causing this tho. –  Oct 11 '21 at 15:24