5

I have this simple angular project and I'm having trouble importing a local json file that I created. Here's the JSON file:

{
    "id": 1,
    "firstName": "Uziel",
    "lastName": "Cabanban",
    "car" : {
        "brand": "Toyota",
        "model": "Vios",
        "year": 2017
    }
}

The JSON file is stored in this directory: src/assets/sampleJson.json.

Here is my component that tries to import said json file:

import { Component, OnInit } from '@angular/core';
import SampleJson from '../assets/sampleJson.json';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

}

I haven't written anything yet as I'm getting a red line in the import SampleJson from '../assets/sampleJson.json

Any suggestion will be much appreciated

Uzi
  • 443
  • 6
  • 33
  • Will you write out the path of your app.component.ts file? Perhaps the relative path '../assets/' is not a legal relative path. – Keenan Diggs Jul 22 '19 at 08:37
  • `app.component.ts` is in `/src/app/app.component.ts` while the json file is in `/src/assests/sampleJson.json`. The `assets` folder was automatically generated when I generated the angular project. I didn't manually create it. – Uzi Jul 22 '19 at 14:09

2 Answers2

9

Thanks for all of the suggestions but I went another direction and didn't use import anymore. Instead I used require and I used it like this:

import { Component } from '@angular/core';
import { user } from './user.model';

declare var require: any;

var myUser: user = require('../assests/sampleJson.json');

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor () {
    console.log(myUser);
  }
}

So far it prints the contents of my json file

Uzi
  • 443
  • 6
  • 33
8

.json file is not a TypeScript module. Since you want local file (assuming it is hardcoded), you can do it by creating a .ts file and export a constant/variable from it like following:

sampleJson.ts

export const SampleJson = {
    "id": 1,
    "firstName": "Uziel",
    "lastName": "Cabanban",
    "car" : {
        "brand": "Toyota",
        "model": "Vios",
        "year": 2017
    }
}

Then in the component:

import SampleJson from '../assets/sampleJson';  // path can change

Hope this helps


More on TypeScript Modules: https://www.typescriptlang.org/docs/handbook/modules.html


Update

Or you can import a JSON file using

import * as SampleJSON from 'path/to/json/sampleJson.json

with TypeScript v2.9.+ according to this answer:

https://stackoverflow.com/a/50674344/1331040

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35