RyanIndustries8
RyanIndustries8

Reputation: 157

Importing json file resulting in a parsing Error for HttpClient

I'm new to learning Angular and what seems like a simple solution for importing an external array is causing an error I just don't understand. I've used AngularJS and didn't have any of these issues. Below is the error I'm receiving

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:4200/assets/models.json", ok: false, …}
error
:
{error: SyntaxError: Unexpected token l in JSON at position 10 at JSON.parse (<anonymous>) at XMLHtt…, text: "[↵  {↵    label: "Metal Man",↵    sample: "/assets…es",↵    textures: "6",↵    materials: "1"↵  }↵]↵"}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
:
"Http failure during parsing for http://localhost:4200/assets/models.json"
name
:
"HttpErrorResponse"
ok
:
false
status
:
200
statusText
:
"OK"
url
:
"http://localhost:4200/assets/models.json"
__proto__
:
HttpResponseBase

In my ts file I have the following request being made from the assets folder-

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-work',
  templateUrl: './work.component.html',
  styleUrls: ['./work.component.css']
})
export class WorkComponent implements OnInit {

  viewMode = 'work';
  modelwork: any;


 constructor( private http: HttpClient, public sanitizer: DomSanitizer ) {
 this.sanitizer = sanitizer;
}

ngOnInit(): void {
this.http.get<any>('./assets/models.json').subscribe(
  data => {
    this.modelwork = data;
  })

$(document).ready(function() {
  $(".tag").hide();
  $(".grid-item").hover(function() {
    $(this).children(".tag").stop(true, true).slideToggle(500);
     return false;
  })
});

}
}

I would very much like to understand what causes this issue, how it can be resolved, and if there is any good documentation on this would be great. I'm using a book called ngBook for my learning platform along with a video series from Lynda. Both seem to lack a lot of information on error issues. I've tried Git, but what I'm looking at as solutions do not quite make sense to me. I'm hoping to learn from this mistake and would appreciate any guidance the community has to offer. Thank you to all who respond in advance!

Upvotes: 0

Views: 475

Answers (1)

machinehead115
machinehead115

Reputation: 1657

From the error it looks like your model.json is not valid JSON. Try putting double quotes around all of your keys.

[
  {
    "label": "Metal Man",
    "sample": "/assets…es",
    "textures": "6",
    "materials": "1"
  }
]

Upvotes: 1

Related Questions