Parse the local JSON file and convert it into an array that conforms to an

My goal is to extract data from a local JSON file and store it in an array of InputData type objects. The JSON contains multiple entries, each following the structure of InputData. I attempted to achieve this with the code snippet below.

The issue arises when trying to subscribe, resulting in the error message "TS2339: Property 'subscribe' does not exist on type '{}'."

If subscribing to the JSON is not possible, what alternative approach can be taken to read the entries and populate the array?

    import dataset from "dataset.json";
    
    export interface InputData {
      _id: {
        $oid: String;
      };
      id: String;
      expNumber: Number;
      passed: Boolean;
    }
    
    @Component({
      selector: "app-read-data",
      templateUrl: "./read-data.component.html",
      styleUrls: ["./read-data.component.scss"],
    })
    export class ReadDataComponent implements OnInit {
      
      public data:InputData[];
    
      constructor() {}
    
      ngOnInit(): void {
        this.dataset.subscribe(readData => {
          readData.reduce(t => this.data.push(t));
        });
        console.log("DATA", this.data);
      }

Below is an example of the JSON File:

[{
  "_id": {
    "$oid": "51275"
  },
  "id": "T22F2r",
  "expNumber": 2,
  "passed": false
},{
  "_id": {
    "$oid": "23451"
  },
  "id": "r3322F",
  "expNumber": 2,
  "passed": true
}]

Answer №1

When working with imported JSON data, it is important to note that it is treated as a constant object and not an observable. Simply assigning it should suffice.

public inputData: InputData[] = importedDataset;

Keep in mind that the JSON data would become an observable if fetched using HTTP from the assets folder.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to convert Firebase snapshot JSON data to text format instead of an object in Vue.js

After successfully pulling the data, it shows up as an object in my view: { "-MH8EpUbn1Eu3LdT0Tj0": { "code": "https://www.apesyntax.com", "content": "This is the tut content", "date": "2020- ...

Angular RxJS: The never-ending reduction

I have developed a component that contains two buttons (searchButton, lazyButton). The ngOnDestroy method is defined as follows: public ngOnDestroy() { this.unsubscribe$.next(); this.unsubscribe$.complete(); } I have created two observables from ...

The world of visual content and data interchange: AS3 graphics

Prior to this, I inquired about action script 3 Json request However, my main query is centered around transforming an image into a JSON object. Any suggestions? Thanks! ...

Reacting to shared routes across various layouts

My React application has two layouts: GuestLayout and AuthLayout. Each layout includes a Navbar, Outlet, and Footer, depending on whether the user is logged in: AuthLayout.tsx interface Props { isAllowed: boolean redirectPath: string children: JSX.E ...

Using Angular JS, the JSON method is invoked from a location external to the controller

How can I call an inner method from outside a controller in AngularJS? var app; (function (){ app = angular.module("gallery", []); app.controller("galleryController", ['$scope','$http', function($scope, $http){ var gallery = this; ...

Angular 14 troubleshooting: Issues with using getRawValue() in IndexOf function

In this scenario, I have a straightforward Person interface defined as: import { FormArray, FormControl, FormGroup } from '@angular/forms'; import { Address } from './address'; export class Person { id: FormControl<number>; n ...

The ng2-material library encountered an error: TypeError - the function all_2.Media.hasMedia is not defined

I am encountering issues while trying to integrate ng2-material with Angular 2. Specifically, when utilizing the Sidenav component, I am faced with the following errors: An exception occurred: TypeError: all_2.Media.hasMedia is not a function in [hasMedi ...

In C#, deserializing a JSON string without a field name requires a different approach

Typically, when working with APIs and receiving a Json string, I create a class that matches the structure of the string and then populate that class using JsonConvert.DeserializeObject from Newtonsoft. However, in this particular Json string, one of the ...

Breaking down nested date lists within DataFrame columns to calculate the average hour

Assuming we have the following DataFrame: ID date_time 1 2020-03-13 21:10:56, 2020-06-02 22:18:06, 2020-04-14 22:10:56, 2021-06-02 22:18:06 2 2010-09-13 21:43:09, 2011-05-04 23:08:15,2012-06-04 23:08:16 3 2013-06-14 23:29:17, 2014-08-13 23:20:2 ...

Having trouble adding a test card to the Google Pay testing environment and calculating the order total

How can I display the order total in GooglePay payment sheet? I could not find any documentation on this. Is it possible to do so? Even though I am using the TEST environment, I am unable to add any test card as mentioned in the URL provided below. Additio ...

Exploring the nested JSON field using a map function

Here is an example of JSON data: { "name": "John", "address": { "city": "New York" } } I am wondering how I can convert this JSON into the following DTO using Jackson: final class PersonDto { private final String name; // name private fina ...

Saving a revised JSON file using AngularJS

Currently, I am in the process of developing a phonegap application using AngularJS that relies on a .json file to store an array of entries. The main goal I am aiming for is to enable users to mark specific entries as favorites and then utilize that data ...

Angular and ASP.NET: Successful Http Get Web Api request, but Angular fails to display any retrieved values

I've recently created a basic WebApi using asp.net core, here's a snippet of the code: [HttpGet("GetHomePageData")] public IActionResult GetHomePageData() { HomePageData HomePageData = new HomePageData() { ...

Encountering Issues with Angular 2: Subject Not Functioning Properly in Http Get Request

Within my Angular application, I have a Form Page where employee data can be input and a Grid Page where entered data is displayed. The goal is for new data submitted through the form to automatically populate in the grid. Initially, I am loading existing ...

Problem with Angular Slider

I'm in the process of creating a carousel component in Angular, but I'm facing an issue where the carousel is not appearing as it should. Below is the code for my carousel component. carousel.component.html: <div class="carousel"> ...

Having trouble with AWS, Angular, and Docker integration issues

I have successfully dockerized my Angular app using the following Dockerfile: FROM node:8.9 as node WORKDIR /app COPY package.json /app/ RUN npm install COPY ./ /app/ ARG env=prod RUN npm run build -- --prod --environment $env FROM nginx:1.13 COPY -- ...

Combine numerous JSON files into a single JSON file

I have numerous JSON files that look like this: For example: 1.json {"name": "one", "description": "testDescription...", "comment": ""} test.json {"name": "test", "description": "testDescription...", "comment": ""} two.json {"name": "two", "descript ...

Conditional generic type in return type with Typescript

How can I condition the generic return type when a value is not present? type Foo = {}; class Bar<P extends Foo> { static make<P extends Foo>(a?: P): Bar<P> { return new Bar(); } } Bar.make() // returns Bar<Foo> ...

Back up your Firestore data automatically using scheduled cron jobs!

Recently, I utilized the firestore-backup-restore tool for backing up Firestore data and it worked seamlessly. However, I am unsure how to schedule this process using cron jobs or a similar method. As someone with no prior experience in utilizing cron jobs ...

Using NiFi - Easy steps to send a GET request with JSON using the InvokeHTTP processor

I am attempting to send a GET request with JSON data to https://www.example.com/api/ GET /path/to/data { "abcd": [ "a1", "a2" ] } The URL encoding for this request is as follows: https://www.example.com/api/path/to/data?json=%8B%0B%+..... I ha ...