[英]Read local JSON file in typescript
How can I read a locally stored JSON file into a variable in typescript?如何将本地存储的 JSON 文件读取到 typescript 中的变量中? I have a json file of photos that looks like this:
我有一个看起来像这样的照片 json 文件:
[
{
"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?我正在尝试将文件作为文本读取,然后使用
Json.Parse
但我如何首先将其作为文本读取? I've tried using FileReader.readAsText but it only accepts blob objects.我试过使用 FileReader.readAsText 但它只接受 blob 对象。 Do I need to create a blob object from my filepath or is there a easier way to read local JSON files?
我是否需要从我的文件路径创建一个 blob object 还是有更简单的方法来读取本地 JSON 文件?
If you don't expect the file to change, you can use require('path')
to get it.如果你不希望文件改变,你可以使用
require('path')
来获取它。 It should just return the object;它应该只返回 object; no need to JSON.parse.
无需 JSON.parse。
You can import the json file您可以导入 json 文件
import all from '../../path/to/file.json'
then declare like below for typing然后像下面这样声明输入
const samples = (all as DataType)
You can do it but need to modify tsconfig.json
.您可以这样做,但需要修改
tsconfig.json
。 In tsconfig.json
there is a setting called resolveJsonModule
.在
tsconfig.json
中有一个名为resolveJsonModule
的设置。 By default its value is set to false
.默认情况下,它的值设置为
false
。
TL;DR TL;博士
tsconfig.json
and if resolveJsonModule
is not present in the compilerOptions
then add it as below:tsconfig.json
如果在compilerOptions
中没有resolveJsonModule
则添加如下: "resolveJsonModule": true,
import * as photos from '../../path-to file';
the above changes are sufficient to import the file.上述更改足以导入文件。
Here is the example: Stackblitz Example这是示例: Stackblitz 示例
You need to add this to your tsconfig您需要将此添加到您的 tsconfig
compilerOptions: { ...
"resolveJsonModule": true,
}
And then import it like any module然后像任何模块一样导入它
import myfile from './path/to/json/file.json';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.