0

I have and array in JSON:

[
    {
        "ProductID": 1,
        "ProductName": "Chai",
        "SupplierID": 1,
        "CategoryID": 1,
        "QuantityPerUnit": "10 boxes x 20 bags",
        "UnitPrice": 18,
        "UnitsInStock": 39,
        "UnitsOnOrder": 0,
        "ReorderLevel": 10,
        "Discontinued": false,
        "Category": {
            "CategoryID": 1,
            "CategoryName": "Beverages",
            "Description": "Soft drinks, coffees, teas, beers, and ales"
        },
        "FirstOrderedOn": new Date(1996, 8, 20)
    },
...
]

I want to create array of objects:

export interface IProduct2{
    ProductID: number,
    ProductName: string
}

Attempt to get from HTTP file and parse:

products2$ = this.http.get<IProduct2[]>(this.product2Url)
.pipe(
  map(products =>
    products.map(product => ({
      ...product,
      searchKey: [product.ProductName]
    } as IProduct2))),
  tap(data => console.log('Products 2: ', JSON.stringify(data))),
  catchError(this.handleError)
);  

Display in component:

<p>
  {{products2$ | async | json}}
</p>

Error: "Server returned code: 200, error message is: Http failure during parsing for http://localhost:4200/api/products/products2.json"

So how to parse it properly into array of objects? How to properly display parsing success/errors, so I can figure out which part of JSON is causing issue? If it's a JSON file should be fine formatted.

Demo application with this issue is here: https://github.com/sam-klok/ang-http-data

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
sam sergiy klok
  • 526
  • 7
  • 17
  • Seems the response is not valid json – MikeOne Mar 25 '23 at 19:31
  • Except for the three dots (which I assume to not be present in the actual file), the JSON appears fine. But you can copy and paste the contents of the file into an online parser like https://jsonviewer.stack.hu/ to find the errors yourself. – Heretic Monkey Mar 25 '23 at 19:32
  • Otherwise, you can set tell HttpClient not to parse the response so you can parse it yourself and catch the error. See answers to [Angular 9 HttpErrorResponse 'JSON.Parse error' while response is OK](https://stackoverflow.com/q/63230566/215552) – Heretic Monkey Mar 25 '23 at 19:36
  • I copied JSON from reputable tutorial.. didn't realized that it does faulty. It have TypeScript code in it... I will post detailed answer below. – sam sergiy klok Mar 26 '23 at 00:04

1 Answers1

0

The failure is due to

"FirstOrderedOn": new Date(1996, 8, 20)

You can verify using an online JSON parser like http://json.parser.online.fr/

enter image description here JSON does not allow that, you should rather specify the date as a string in ISO-8601.

As new Date(1996, 8, 20).toJSON() returns 1996-09-19T18:30:00.000Z, you can replace the above date value as below

"FirstOrderedOn": "1996-09-19T18:30:00.000Z"

Related answer: https://stackoverflow.com/a/15952652/3423750

Phalgun
  • 1,181
  • 2
  • 15
  • 42