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

Converting custom JSON data into Highcharts Angular Series data: A simple guide

I am struggling to convert a JSON Data object into Highcharts Series data. Despite my limited knowledge in JS, I have attempted multiple times without success: Json Object: {"Matrix":[{"mdate":2002-02-09,"mvalue":33.0,"m ...

Generate JSON data in C# similar to how PHP's json_encode function works

If I wanted to return JSON in PHP, I could use the following code: return json_encode(array('param1'=>'data1','param2'=>'data2')); What is the simplest way to do the equivalent in C# ASP.NET MVC3? ...

I am currently experiencing a problem with deleting documents in Firebase Firestore using React, Typescript, and Redux. Despite the code running, the document continues to exist in

I seem to be encountering an issue that I can't quite figure out. Despite my code running smoothly, I am unable to delete a document from Firestore. The document ID definitely exists within the database, and there are no subcollections attached to it ...

Unable to allocate information in the subscribe method

I'm experiencing an issue with the post method. Whenever I try to retrieve data using the segmentService, I always receive an empty segmentdata object in my temporarySegment variable. Strangely enough, when I use the same approach for retrieving numbe ...

How can I convert Typescript absolute paths to relative paths in Node.js?

Currently, I am converting TypeScript to ES5/CommonJS format. To specify a fixed root for import statements, I am utilizing TypeScript's tsconfig.json paths property. For instance, my path configuration might look like this: @example: './src/&ap ...

The ASP.NET Core webapi displays an error message titled "SyntaxError: JSON.parse" when a GET request is made

Just a heads up: I am fairly new to learning C# and currently working on constructing an ASP.NET core web API that communicates with an SQL database. Both the API and database are now hosted on Azure... ...and while I am able to successfully make requests ...

What is the best way to showcase a file edited in Emacs within Atom?

The coding project I'm working on is built with Typescript, but I don't believe that's relevant. I've noticed that Emacs has a unique approach to indentation. According to the documentation, in Text mode and similar major modes, the TAB ...

How can I rectify the issue in TypeScript where the error "not all code paths return a value" occurs?

While developing an application, I encountered an error that says: "not all code paths return a value". The error is specifically in the function named addValues, indicating that the function must return "Obj[] | undefined". Here is the code snippet in qu ...

Is there a way to convert a JSON file with a single 'header' row and subsequent 'data' rows, possibly using jq?

I currently have a JSON file structured like this: { "data" : [ { "values" : [ "ColumnHeader1", "ColumnHeader2", "ColumnHeader3" ]}, { "values" : [ "Row1Column1", "Row1 ...

Extracting pagination information from a web service's JSON data

Currently, I am faced with the task of parsing a significant amount of JSON data coming from a remote web service. The data is paginated over 500 URIs, each containing 100 JSON objects. My goal is to compare a specific property in each JSON object, which i ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

What is the best method for translating object key names into clearer and easier to understand labels?

My backend server is sending back data in this format: { firstName: "Joe", lastName: "Smith", phoneNum: "212-222-2222" } I'm looking to display this information in the frontend (using Angular 2+) with *ngFor, but I want to customize the key ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Accessing the Next.js API after a hash symbol in the request URL

Is there a way to extract query strings from a GET request URL that contains the parameters after a '#' symbol (which is out of my control)? For example: http://...onnect/endpoint/#var_name=var_value... Even though request.url does not display a ...

Deploying an Angular application in a NodeJS environment using Azure DevOps

Can Azure DevOps Pipelines be used to automate the deployment of an Angular application to NodeJS or an on-premise WebServer? ...

To reveal more options, simply click on the button to open up a dropdown

I am currently utilizing the Bootstrap 5 CDN and I am looking for a way to automatically open the dropdown menu without having to physically click on it. Within the navbar, I want to display the "Dropdown Link": <nav class="navbar navbar-expand-sm ...

"Efficiently Distributing HTTP Requests Among Simultaneous Observers using RxJS

Currently, I am working on a feature in my Angular application that requires handling multiple concurrent fetches for the same data with only one HTTP request being made. This request should be shared among all the subscribers who are requesting the data s ...

The module imported by Webpack appears to be nothing more than a blank

I am attempting to integrate the "virtual-select-plugin" library into my Typescript project using webpack. Unfortunately, this library does not have any type definitions. Upon installation via npm, I encountered the following error in the browser: TypeErro ...

Importing Angular Material modules

I've integrated the Angular Material module into my project by updating the material.module.ts file with the following imports: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatT ...

Comparing Perl multithreading with JSON manipulation

I encountered an issue with the program below, resulting in the following error message: JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this) at json_test.pl line 10. The program runs withou ...