I am trying to import a .json file into Typescript as an array and do not know how to grab the values.
import * as data from './list.json';
const array = data;
console.log(array);
My json file
[
"Element 1",
"Element 2",
"Element 3",
"Element 4",
"Element 5"
]
This is what the variable array looks like in the console when I am trying to log it in console. I can see that all elements from the array are there under default: But I do not know how to access that. I have tried array[0] and that is undefined
Module
default: Array(5)
0: "Element 1"
1: "Element 2"
2: "Element 3"
3: "Element 4"
4: "Element 5"
length: 5
[[Prototype]]: Array(0)
__esModule: true
Symbol(Symbol.toStringTag): "Module"
CodePudding user response:
There are a few ways you can import json.
import json from "file.json";
import json = require("file.json");
import * as json from "file.json";
You can use whichever you want. The first one is preferred.
CodePudding user response:
One way to import the default export is this syntax
import data from './list.json';
const array = data;
console.log(array);
But you should also be able to access the array elements with your import method:
import * as data from './list.json';
const array = data;
console.log(array[1]); // 'Element 2'
CodePudding user response:
don't import .json, instead use typescript module/const and export it
like create data.ts
data.ts
export const DUMMY_DATA = [
'Element 1',
'Element 2',
'Element 3',
'Element 4',
'Element 5',
];
and import this into your typescript file
like
import { DUMMY_DATA } from './data';
console.log(DUMMY_DATA);
DUMMY_DATA.forEach((item) => {console.log(item)});