如何将 JSON 文件导入 TypeScript 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46991237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import JSON File into a TypeScript file?
提问by aonepathan
I am building a map application using Angular Maps and want to import a JSON file as a list of markers defining locations. I'm hoping to use this JSON file as marker[] array inside the app.component.ts . Instead of defining a hardcoded array of markers inside the TypeScript file.
我正在使用 Angular Maps 构建地图应用程序,并希望将 JSON 文件作为定义位置的标记列表导入。我希望将此 JSON 文件用作 app.component.ts 中的标记 [] 数组。而不是在 TypeScript 文件中定义一个硬编码的标记数组。
What is the best process of importing this JSON file for use in my project? Any direction greatly appreciated!
导入此 JSON 文件以在我的项目中使用的最佳过程是什么?任何方向不胜感激!
回答by ryanrain
Aonepathan's one-liner was working for me until a recent typescript update.
Aonepathan 的 one-liner 一直在对我来说有效,直到最近的打字稿更新。
I found Jecelyn Yeen's postwhich suggests posting this snippet into your TS Definition file
我发现 Jecelyn Yeen 的帖子建议将此代码段发布到您的 TS 定义文件中
add file typings.d.tsto the project's root folder with below content
将文件添加typings.d.ts到项目的根文件夹中,内容如下
declare module "*.json" {
const value: any;
export default value;
}
and then import your data like this:
然后像这样导入你的数据:
import * as data from './example.json';
import * as data from './example.json';
update July 2019:
2019 年 7 月更新:
Typescript 2.9 (docs) introduced a better, smarter solution. Steps:
Typescript 2.9 ( docs) 引入了更好、更智能的解决方案。脚步:
- Add
resolveJsonModulesupport with this line in yourtsconfig.jsonfile:
resolveJsonModule在您的tsconfig.json文件中使用此行添加支持:
"compilerOptions": {
...
"resolveJsonModule": true
}
the import statement can now assumes a default export:
import 语句现在可以假设默认导出:
import data from './example.json';
import data from './example.json';
and intellisense will now check the json file to see whether you can use Array etc. methods. pretty cool.
并且智能感知现在将检查 json 文件以查看您是否可以使用 Array 等方法。很酷。
回答by Benjamin Caure
Here is complete answer for Angular 6+ based on @ryanrain answer:
这是基于@ryanrain 答案的 Angular 6+ 的完整答案:
From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.
从angular-cli doc 中,json 可以被视为资产,可以从标准导入访问,而无需使用 ajax 请求。
Let's suppose you add your json files into "your-json-dir" directory:
假设您将 json 文件添加到“your-json-dir”目录中:
add "your-json-dir" into angular.json file (:
"assets": [ "src/assets", "src/your-json-dir" ]create or edit typings.d.ts file (at your project root) and add the following content:
declare module "*.json" { const value: any; export default value; }This will allow import of ".json" modules without typescript error.
in your controller/service/anything else file, simply import the file by using this relative path:
import * as myJson from 'your-json-dir/your-json-file.json';
将“your-json-dir”添加到 angular.json 文件中(:
"assets": [ "src/assets", "src/your-json-dir" ]创建或编辑typings.d.ts 文件(在您的项目根目录下)并添加以下内容:
declare module "*.json" { const value: any; export default value; }这将允许导入“.json”模块而不会出现打字稿错误。
在您的控制器/服务/任何其他文件中,只需使用此相对路径导入文件:
import * as myJson from 'your-json-dir/your-json-file.json';
回答by aonepathan
Thanks for the input guys, I was able to find the fix, I added and defined the json on top of the app.component.ts file:
感谢您的输入,我能够找到修复程序,我在 app.component.ts 文件顶部添加并定义了 json:
var json = require('./[yourFileNameHere].json');
This ultimately produced the markers and is a simple line of code.
这最终产生了标记,并且是一行简单的代码。
回答by Yulian
As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:
正如这篇 reddit 帖子中所述,在 Angular 7 之后,您可以将事情简化为以下 2 个步骤:
- Add those three lines to
compilerOptionsin yourtsconfig.jsonfile:
- 将这三行添加到
compilerOptions您的tsconfig.json文件中:
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
- Import your json data:
- 导入您的 json 数据:
import myData from '../assets/data/my-data.json';
And that's it. You can now use myDatain your components/services.
就是这样。您现在可以myData在您的组件/服务中使用。
回答by vicbyte
First solution- simply change the extension of your .json file to .ts and add export defaultat the beginning of the file, like so:
第一个解决方案- 只需将 .json 文件的扩展名更改为 .ts 并export default在文件开头添加,如下所示:
export default {
property: value;
}
Then you can just simply import the file without the need to add typings, like so:
然后你可以简单地导入文件而无需添加类型,如下所示:
import data from 'data';
Second solutionget the json via HttpClient.
第二种解决方案通过 HttpClient 获取 json。
Inject HttpClient into your component, like so:
将 HttpClient 注入您的组件,如下所示:
export class AppComponent {
constructor(public http: HttpClient) {}
}
and then use this code:
然后使用此代码:
this.http.get('/your.json').subscribe(data => {
this.results = data;
});
This solution has one clear adventageover other solutions provided here - it doesn't require you to rebuild entire application if your json will change (it's loaded dynamically from a separate file, so you can modify only that file).
与此处提供的其他解决方案相比,此解决方案有一个明显的优势- 如果您的 json 发生变化,它不需要您重新构建整个应用程序(它是从单独的文件动态加载的,因此您只能修改该文件)。
回答by Ian Jamieson
I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.
我已经阅读了一些回复,但它们似乎对我不起作用。我正在使用 Typescript 2.9.2、Angular 6 并尝试在 Jasmine 单元测试中导入 JSON。这就是对我有用的技巧。
Add:
添加:
"resolveJsonModule": true,
To tsconfig.json
到 tsconfig.json
Import like:
导入如:
import * as nameOfJson from 'path/to/file.json';
Stop ng test, start again.
停止ng test,重新开始。
Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports
参考:https: //blogs.msdn.microsoft.com/typescript/2018/05/31/annoucing-typescript-2-9/#json-imports
回答by Stevemaster92
For Angular 7+,
对于 Angular 7+,
1) add a file "typings.d.ts" to the project's root folder (e.g., src/typings.d.ts):
1) 在项目的根文件夹中添加一个文件“typings.d.ts”(例如,src/typings.d.ts):
declare module "*.json" {
const value: any;
export default value;
}
2) import and access JSON data either:
2) 导入和访问 JSON 数据:
import * as data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
constructor() {
console.log(data.default);
}
}
or:
或者:
import data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
constructor() {
console.log(data);
}
}
回答by Kodjo Tchioffo
In angular7, I simply used
在 angular7 中,我只是简单地使用了
let routesObject = require('./routes.json');
My routes.json file looks like this
我的 routes.json 文件看起来像这样
{
"routeEmployeeList": "employee-list",
"routeEmployeeDetail": "employee/:id"
}
You access json items using
您使用访问 json 项目
routesObject.routeEmployeeList
回答by Nigel Gilbert
As of Typescript 2.9, one can simply add:
从Typescript 2.9 开始,可以简单地添加:
"compilerOptions": {
"resolveJsonModule": true
}
to the tsconfig.json. Thereafter, it's easy to use a json file (andthere will be nice type inference in VSCode, too):
到tsconfig.json. 此后,使用 json 文件很容易(而且VSCode 中也会有很好的类型推断):
data.json:
data.json:
{
"cases": [
{
"foo": "bar"
}
]
}
In your Typescript file:
在您的打字稿文件中:
import { cases } from './data.json';
import { cases } from './data.json';
回答by Fateh Mohamed
let fs = require('fs');
let markers;
fs.readFile('./markers.json', handleJSONFile);
var handleJSONFile = function (err, data) {
if (err) {
throw err;
}
markers= JSON.parse(data);
}

