Read local JSON file in typescript
Asked Answered
I

4

7

How can I read a locally stored JSON file into a variable in typescript? I have a json file of photos that looks like this:

[
    {
      "id": 1,
      "camera": "",
      "location": "",
      "iso": 0,
      "aperture": 0,
      "focal length": 0
    },
    {
      "id": 2,
      "camera": "",
      "location": "",
      "iso": 0,
      "aperture": 0,
      "focal length": 0
    },
    {
      "id": 3,
      "camera": "",
      "location": "",
      "iso": 0,
      "aperture": 0,
      "focal length": 0
    }
]

I'm trying to read the file as text and then use Json.Parse but how do I read it as text in the first place? I've tried using FileReader.readAsText but it only accepts blob objects. Do I need to create a blob object from my filepath or is there a easier way to read local JSON files?

Iridescence answered 4/6, 2021 at 17:25 Comment(7)
what do you mean by locally stored ? is it on your machine or in codebase ?Rambler
A simple import should do itWrongdoing
It's stored in the codebaseIridescence
@Wrongdoing I've tried import photos from "./assets/photos.json" but it says it cant find the moduleIridescence
In the codebase and bundled with the code, right?Impalpable
@CameronCheung check my answer with example : https://mcmap.net/q/1408034/-read-local-json-file-in-typescriptRambler
Does this answer your question? Importing JSON file in TypeScriptSprightly
R
14

You can do it but need to modify tsconfig.json. In tsconfig.json there is a setting called resolveJsonModule. By default its value is set to false.

TL;DR

  1. Open tsconfig.json and if resolveJsonModule is not present in the compilerOptions then add it as below:
    "resolveJsonModule": true,
    
  2. Open the component where you want to read the file and import like:
    import * as photos from '../../path-to file';
    

the above changes are sufficient to import the file. Here is the example : Stackblitz Example

Rambler answered 4/6, 2021 at 17:53 Comment(0)
B
3

You can import the json file

import all from '../../path/to/file.json'

then declare like below for typing

const samples = (all as DataType)
Benbena answered 4/6, 2021 at 17:52 Comment(0)
O
1

If you don't expect the file to change, you can use require('path') to get it. It should just return the object; no need to JSON.parse.

Outstretched answered 4/6, 2021 at 17:45 Comment(0)
W
1

You need to add this to your tsconfig

compilerOptions: { ... 
  "resolveJsonModule": true,
}

And then import it like any module

import myfile from './path/to/json/file.json';
Wrongdoing answered 4/6, 2021 at 17:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.