I'm having problems to import JSON data into my angular application.
What I'm doing:
- Import the json file into a variable:
import _datos from '../../../assets/data.json';
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.
Declaring an interface in order to improve the readability of the code:
export interface Datos{
property1: String,
property2: String,
etc.
}
- 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.
CodePudding user response:
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.
CodePudding user response:
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.