Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Array from JSON File into Typescript File

I have a JSON file which contains an array object as such :

[
  {
    "VergiNo": "XXXXXXX"
  },
  {
    "VergiNo": "YYYYYY"
  },
  {
    "VergiNo": "ZZZZZZ"
  }
]

and I import this JSON file to my Typescript file

import * as firmalar from "../firmalar.json";

const firmaPromises = firmalar.map((firma) => firma.VergiNo + "XYZ");

Above code gives no syntax error, however when I run the application and debug it, firmalar object is seen as object not an array, so it doesn't process map method.

Is there anything wrong that I'm doing here?

like image 623
serkanz Avatar asked Aug 31 '26 05:08

serkanz


1 Answers

To import the JSON data, you should use:

import firmalar from "../firmalar.json";

This will import it without changing it, and you'll get an array.

When you did the import with * as firmalar it tries to convert the JSON into a module, which is a kind of Object. Inspecting it you'll see it has Object style accessors, so that firmalar[0] will work, but firmalar.length will not.

like image 167
Piran Avatar answered Sep 02 '26 20:09

Piran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!