简体   繁体   中英

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?

I would try to parse the JSON. That should return you an array.

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

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

You're importing a whole module.

You can either import only that constant:

import { yourArray } from "../firmalar.json";

Or extract the array from the module:

const firmalarArray = JSON.parse(firmalar.yourArray);

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.

I ended up with using require() to get JSON and cast it to my object after that like this :

// eslint-disable-next-line @typescript-eslint/no-var-requires
const firmalar = require("./firmalar.json");

// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const firmalarArray: { VergiNo: string }[] = firmalar;

Now it works as expected. This post helped me to find the solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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