【问题标题】:Read JSON file from file in Angular从 Angular 中的文件中读取 JSON 文件
【发布时间】:2021-08-27 18:23:35
【问题描述】:

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

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

我必须读取文件并在不解析的情况下获取 JSON 文件的内容。

搜索了一下,有两种方法

  1. "resolveJsonModule": true 添加到tsconfig.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?

【问题讨论】:

  • 这能回答你的问题吗? Angular 5 Service to read local .json file
  • @R.Richards 这实际上并没有回答我的问题。使用HttpClient 将在没有连接时停止工作,并且它需要将数据文件放在assets 目录中,而在我的情况下,它在其模块目录中。
  • 看起来 jsonModule 应该始终是一个对象。您可以尝试 { data: [ "caseSensitive", "matchKeywords", "items" ]} 然后导入为 import { data } from './app/config/config.json';

标签: json angular typescript


【解决方案1】:

您可以使用@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. 大多数编辑器会为您自动完成

【讨论】:

    【解决方案2】:

    在 Angular 中,要将 JSON 作为对象访问,您需要在 tsconfig.json 文件中添加以下两个选项:

    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    

    然后你可以像下面这样在你的服务中导入它:

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

    【讨论】:

      【解决方案3】:

      要在 Angular 中将 JSON 作为模块访问,您应该将这两行添加到 tsconfig.json 文件中

      "resolveJsonModule": true,
      "allowSyntheticDefaultImports": true
      

      然后你可以在应用内任何你想要的地方导入它

      import  *  as  Characters  from  './configs/characters.json';
      

      最终从模块中访问对象

      export class CharactersComponent {
          public characters: CharacterModel[] = (Characters as any).default;
      }
      

      【讨论】:

        猜你喜欢
        • 2013-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-11
        • 2020-01-21
        • 1970-01-01
        相关资源
        最近更新 更多