A step-by-step guide on reading/loading a JSON file using Typescript

I'm fairly new to Typescript and I'm attempting to parse a simple JSON file using Typescript. After searching online and testing different solutions, I still haven't been able to find a straightforward code snippet that reads a local JSON file into a numeric array variable. The content of the JSON file is as follows: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 16.4, 194.1, 95.6, 54.4].

If anyone could provide me with some guidance on this issue, I would greatly appreciate it.

Best regards, GF

Answer №1

Start by creating a JSON file in a designated folder, such as properties.json.

{ 
"url" : "https://github.com/microsoft/TypeScript/blob/main/package.json?msclkid=3b7f06f5d0e111eca3cc1f08a914ff77",
person: {
   "firstname":"yuvraj",
   "lastname" : "thorat"
}
}

Next, to read the JSON file, you need to create a file within your project folder called readjson.ds.ts

declare module "*.json" {
   const value : any;
   export default value
}

Now you can access this JSON data within your project from a different file.

To do so, add an import statement like the one below and reference the desired JSON properties.

---------------------------------------------------
import * as prop from "../testdata/properties.json"

siteUrl =  (<any>prop).url;
----------------------------------------------------

That's it! You should now be able to access all remaining properties in a similar manner.

Answer №2

Using Standard JavaScript -

let jsonData = "[29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 16.4, 194.1, 95.6, 54.4]";
let arrayData = JSON.parse(jsonData);

(edit)

I recently came across the requirement for a "local file" incorporation. If you need to do this at compile time, simply prefix the JSON data in the file with the variable name and nothing else is required - just a basic window.json = ... will suffice - no quotes needed. For runtime inclusion, the file needs to be loaded either through AJAX or by adding the variable-prefixed file within a

<script type="text/javascript" src="file.json"></script>
tag.

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

Interacting with child collections data in C# through a RESTful API using Entity Framework context

Utilizing projection (explicit loading) to fetch and filter collection data from a child table via a RESTful Api service results in the JSON repeating the child table collections object. However, using the "AsNoTracking()" method eliminates the nested chil ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Enhance constructor functionality in Ionic 4 by incorporating additional parameters

Recently, I started using Ionic and came across a location page. In the location/location.page.ts file, there was an automatically generated empty constructor like this: constructor() { } Initially, the page functioned properly with this setup. However, ...

Issue with unapplied nullable type during export操作

I'm struggling to understand why my nullable type isn't being applied properly Here's an illustration interface Book { name: string; author: string; reference: string; category: string; } async function handleFetch<T>(endpoin ...

Apollo GraphQL has initiated the detection of a new subscription

My approach involves utilizing graphql-ws for subscribing to GraphQL events. I rely on the Observable interface to listen to these events. Although I can use the error callback to identify when a subscription fails to start, it is challenging to determine ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

How to parse an array in JSON using Swift 3 and iterate through it

Figuring out how to parse JSON data in Swift 3 has been more challenging than I anticipated, especially coming from a Javascript background. Received response from API: [ { "ID": 1881, "image": "myimageURL", }, { "ID": 6333, "image": "myi ...

Showing a loading overlay during an AJAX call on a JSP page

Hello there! I'm interested in adding a special effect to my JSP page's center when making an ajax call to load a dropdown menu. Can anyone help me with this? Thanks! ...

The reason behind my struggle with mapping API responses to an Interface in Angular

Hello everyone, I am currently working on mapping some API responses from The Muse API to an APIResponseInterface that I have created. Here's a snippet of my code: Service that sends the request: getJobs(page: number): Observable<APIResponseInterf ...

Converting ASP .Net Core Dto's and Controllers into TypeScript classes and interfaces

My concept involves incorporating two key elements: Converting C# Dto's (Data-transfer-objects) into TypeScript interfaces to ensure synchronization between client-side models and server-side. Transforming ASP .Net Core controller endpoints into Typ ...

The attribute 'data' is not found in the type 'IntrinsicAttributes & IProps'. Error code: ts(2322)

I encountered the following issue: Error: Type '{ data: never; }' is not compatible with type 'IntrinsicAttributes & IProps'. The property 'data' does not exist on the type 'IntrinsicAttributes & IProps'. import { ...

Issues arise when attempting to assign GraphQL types, generics, and NestJS Type<> as they are not interchangeable with Type<&

I've been attempting to use this definition: import { GraphQLScalarType } from 'graphql'; import { Type } from '@nestjs/common'; export function createFilterClass<T extends typeof GraphQLScalarType>( FilterType: Type&l ...

What is the best way to save and access multiple arrays within a single object in local storage?

I am looking to streamline my code by combining 5 arrays into a single object and storing it in local storage. However, when trying to retrieve the object later on, the properties are showing up as undefined. To address this issue, I want to push an object ...

AngularJS login form with JSON data

I am currently learning Angular and focusing on the login form implementation. The specific model I am working with can be found in this PLNKR. There are two challenges that I am struggling to resolve. Issue 1: I'm trying to figure out how to tur ...

Utilize Angular's grep or filter method to retrieve an object based on its unique identifier

I have a collection of Category objects stored as a JSON array in vm.data within my controller for an Angular repeater. Now, I want to access the SubCats within each category by using the 'Category' field in each SubCat. Below is a generic funct ...

I would like to know the best way to compare two JSON data sets, filter out any matching data, and then store the remaining results

To efficiently extract all Post Titles from a JSON API, I am utilizing another JSON API of users to further retrieve the count of comments for each Post. Here are the APIs being used: API for USERS: http://jsonplaceholder.typicode.com/users API for POSTS ...

In TypeScript, deduce the optional generic type automatically

Feeling a bit out of my depth here. I need to perform an inference on a generic that includes an optional "parse" function which returns the formatted value [or throws]. They say code speaks louder than words, so let's take a look at the example: exp ...

Get javax.json by utilizing Maven

I'm working on integrating the javax.json library into my project, so I included it in my pom.xml file as follows: <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <versio ...

Are ngFormModel characteristics subject to change?

I've been facing challenges while working with ngFormModel and dynamic properties from classes. Despite my efforts, I'm unable to update the ngFormModel when changing variables to reflect new values. You can see an example of this issue in the fo ...