Reputation: 451
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?
Upvotes: 6
Views: 6801
Reputation: 7328
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.
Upvotes: 10
Reputation: 451
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.
Upvotes: 2
Reputation: 2548
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");
Upvotes: 1
Reputation: 10137
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);
Upvotes: 1