首页 > 解决方案 > 从 Angular 中的文件中读取 JSON 文件

问题描述

config.json在目录中保存了一个 JSON 文件src/app/config

[
  "caseSensitive",
  "matchKeywords",
  "items"
]

我必须读取文件并获取 JSON 文件的内容而不对其进行解析。

搜索后,我有两种方法

  1. 添加"resolveJsonModule": truetsconfig.json文件
  2. 声明一个打字模块declare module "*.json" {}

并将 JSON 导入为

import * as data from './app/config/config.json';


export class SchemaService {

  constructor() { }

  getConfig() {
    console.log('bool: ', data);                         // Output in screenshot
    console.log('type: ', typeof BooleanData);           // object
    console.log('parsed: ', JSON.stringify(BooleanData));
  }
}

但是这两种方式都将解析的输出作为

在此处输入图像描述

JSON.stringify(BooleanData)语句没有给出实际的 JSON 文件,而是将数组项更改为键值,其中索引表示为键

{
  "0":"caseSensitive",
  "1":"matchKeywords",
  "2":"items"
}

如何在 Angular 中读取原始 JSON(无需解析),或者至少将对象转换为 JSON?

标签: jsonangulartypescript

解决方案


您可以使用@amer-yousuf 提供的快速修复,但它也可以让您将任何.js文件导入您的代码库。我不会喜欢那个。这是另一种方法

定义您的config.json.ts(注意它以.ts而不是结尾.json)如下所示

export const CONFIG = { // your JSON is assigned to CONFIG variable
    "say": "hello world"
}

.ts在您要使用的其他文件中,使用类似以下代码的内容

import { CONFIG } from './config.json';

// ...

console.log(CONFIG.say);

// ...

这种方法的好处:

  1. 你仍然可以在 config.json.ts 上使用 tslint/eslint
  2. 大多数编辑器会为您自动完成

推荐阅读