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"
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.
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'
I was using:
import * as items from 'file.json';
console.log(`>>>`, Array.isArray(productDetails));
console.log(`>>>`, Object.keys(productDetails));
returns an Object that has numerical keys (like an Array) but that is not an Array:
console.log
>>> false
at Object.<anonymous> (src/lib/file.ts:67:9)
console.log
>>> [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19',
'20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
'30', '31', '32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47', '48', '49',
'50', '51', '52', '53', '54', '55', '56', '57', '58', '59',
'60', '61', '62', '63', '64', '65', '66', '67', '68', '69',
'70', '71', '72', '73', '74', '75', '76', '77', '78', '79',
'80', '81', '82', '83', '84', '85', '86', '87', '88', '89',
'90', '91', '92', '93', '94', '95', '96', '97', '98', '99',
... 1410 more items
]
As you can see, the object was importing as an plain Object, not an Array.
Changing the import to:
import items from 'file.json';
Resolved the issue, importing items as an Array.