6

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?

1
  • 1
    firmalar.json file return string just parse it with JSON.parse(firmalar). Commented Mar 12, 2020 at 8:59

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This works great! However you need to add the allowSyntheticDefaultImports flag to your tsconfig.json and set it to true
2

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.

Comments

1

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);

Comments

1

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");

1 Comment

this gives a syntax error as firmalar isn't recognized as string. Even if I use : const firmalarArray: [{ VergiNo: string }] = JSON.parse(firmalar.toString()); it doesn't work in runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.