Lee9287
Lee9287

Reputation: 407

Convert JSON file to Typecript Array of Objects

I am reading in a JSON file and attempting to convert them to an array of objects. I get a syntax error on the component file.

This is the component code

import * as blogs from '../story/stories.json';
import { IStory } from '../models/story';

@Component({
  selector: 'app-story',
  templateUrl: './story.component.html',
  styleUrls: ['./story.component.scss']
})
export class StoryComponent implements OnInit {
  stories: IStory[] ;
  constructor() { }

  ngOnInit() {
    this.stories = blogs; <-- syntax error on this line
      
  }

this is the story.ts file:

export interface IStory {
    id: number;
    author: string;
    title: string;
    pictureUrl: string;
    body: string;
  }

This is the JSON file, stories.json:

[
{"date":3,"author":"AVC", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"},
{"date":4,"author":"ADF", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"}
]

Upvotes: 0

Views: 30

Answers (1)

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17610

Demo try to map to interface

this.stories = this.blogs.map(x=> {return {author:x.author,title:x.title,pictureUrl:x.pictureUrl,body:x.body,id:null}});

Upvotes: 1

Related Questions