Anuj TBE
Anuj TBE

Reputation: 9806

Read JSON file from file in Angular

I have a JSON file config.json saved in the src/app/config directory.

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

I have to read the file and get the content of the JSON file without parsing it.

After searching for it, I got two ways

  1. Add "resolveJsonModule": true to the tsconfig.json file
  2. Declara a typing module declare module "*.json" {}

and importing JSON as

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));
  }
}

But both the ways are giving the parsed output as

enter image description here

The JSON.stringify(BooleanData) statement is not giving the actual JSON file, instead, the array items are changed to key-value where the index is represented as key

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

How can I read the raw JSON (without parsing) in Angular, or at least convert an object into JSON?

Upvotes: 0

Views: 2107

Answers (3)

Klodian
Klodian

Reputation: 713

To access JSON as Module in Angular you should add these two lines into tsconfig.json file

"resolveJsonModule": true,
"allowSyntheticDefaultImports": true

Then you can import it anywhere you want within the app

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

Finaly access the object from module

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

Upvotes: 2

Jp Vinjamoori
Jp Vinjamoori

Reputation: 1271

You can use a quickfix provide by @amer-yousuf But it will also let you import any .js file into your codebase as well. I wont prefer that. Here is an alternative approach

Define your config.json.ts (notice it ends with .ts and not .json) something like below

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

In your other .ts file where you want to use, use something like following code

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

// ...

console.log(CONFIG.say);

// ...

Benefit of this method:

  1. You can still use tslint/eslint on config.json.ts
  2. Most editors will auto-complete for you

Upvotes: 2

Amer
Amer

Reputation: 6716

In Angular, to access the JSON as an object, you need to add the following two options to the tsconfig.json file:

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

Then you can import it within your service like the following:

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

Upvotes: 2

Related Questions