Using TypeScript to import a JSON file and assign it to a variable defined by an interface

Here is a snippet of the JSON file (test.json) I am working with:

{"test":[
    {"file": "f1.txt", "nr":3},
    {"file": "f4.txt", "nr":4},
    {"file": "f7.txt", "nr":7}
]}

In TypeScript, I've created an interface to represent this JSON structure:

export interface IJsonFiles {
    test: (FileEntity)[];
}

interface FileEntity{
    file: string;
    nr: number;
}

To properly import the JSON in my TypeScript code, I had to include a json.d.ts file like so:

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

Now, when trying to import test.json into my code using the following statement:

import * as b from '../../assets/test.json';
let files: IJsonFiles;
files = b;

I encounter the following error message:

TS2322: Type 'typeof import("*.json")' is not assignable to type 'IJsonFiles'.  Property 'test' is missing in type 'typeof import("*.json")'.

If anyone can provide assistance, it would be greatly appreciated. The end goal is to import JSON files without using require and to have the JSON structure defined properly in TypeScript.

Answer №1

Incorporating JSON data with type definitions in Node v10.16.0 and TypeScript v3.6.3 is a crucial step.

venues.json

[
  {
    "id": "c29e3ee4b23342db8afdab4c826ab478",
    "name": "Example",
    "hostnames": [
      "example.com"
    ],
    "shortcode": "example",
    "lickstatsUrl": "https://theregs.co/example",
    "pin": "1234"
  },
  ...
]

index.ts

Implementing the necessary type structure to import the 'venues.json' file effectively.

const VenueStructure: venue = {
  id: string;
  hostnames: string[];
  shortcode: string;
  lickstatsUrl: string;
  pin: string;
}

const venuesCollection = _venues as VenueStructure[];

Answer №3

To create a new object using an interface, you can follow these steps:

import venuesData from './venues.json';

interface IVenue {
  id: string;
  hostnames: string[];
  shortcode: string;
  lickstatsUrl: string;
  pin: string;
}

const venuesObject: Venue = venuesData;

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

Can you explain the significance of the syntax provided?

I've been going through the Angular tutorial, but I'm having trouble grasping the significance of this particular code snippet: return (error: any): Observable<T> => {...}; It seems like the function is returning another function, but ...

Retrieve the entirety of the HTML document and then extract the JSON section within it

Looking to extract a table from the following URL: using VBA. The challenge here lies in the fact that the table consists of JSON data embedded within an HTML file. Following @Tomalak’s advice, I have broken down the task into four individual steps: S ...

Having trouble with error popups in Typescript 3.7.2, React, and Material UI 4.5.1 Snackbars due to styling errors

Utilizing the material UI snackbar for displaying error pop-ups in my react application has been quite a challenge. Incorporating a container view where certain actions trigger errors, I aimed to implement my custom snackbar component when an error arises ...

Retrieving JSON data through the use of retrofit and rxjava

I'm trying to retrieve JSON data from a specific URL using Retrofit and RxJava. You can find the sample JSON data at this link: . Here's a snippet of the JSON: { "data": [ { "itemId": "1", "desc": "Batcave", "audio": "https://storage.googl ...

In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a ...

Ways to retrieve the JSON id once an item has been generated

My current project involves utilizing a function to share a collection of bookmarks among users. I am working with the WordPress UserPro Bookmarks plugin and need assistance in obtaining the ID after a new item is created. function share_collection($id,$n ...

Developing a custom HTTP request class in Angular 2 and its exporting capabilities

I have created a simple HTTP requests class using Angular 2: http-handler.ts import {Http, Headers, RequestOptions} from 'angular2/http' import {Injectable} from 'angular2/core'; import 'rxjs/add/operator/toPromise'; @Injec ...

Can a custom type be created in Typescript that permits objects but excludes Errors?

Currently working on resolving an odd scenario with a logger. Essentially, calls like log({ info: 'information' }) function as expected, but log(new Error()) falls short. While no solution is readily available, the goal is to override the log m ...

The animation in ThreeJs encounters context issues within Angular 2

I am trying to incorporate ThreeJs into my Angular 2 project. I have successfully rendered a scene with a simple cube, but I ran into an issue when using the animate() function. Here is the code snippet: import { OnInit, Component } from '@angular/co ...

What are the steps to upload multiple json files onto Google App Engine?

Recently, I encountered slow loading times when trying to store a json file on my website server for use in a mobile app. After some research, I came across the idea of hosting the json file on Google App Engine to potentially speed up the process. Can som ...

Converting JSON information into a JavaScript array of objects

I have a JSON file containing placeholder articles for testing purposes. I'm using jQuery to parse the data from the JSON file and create an array of objects with the retrieved information. Take a look at my JSON file: { "news": [ { ...

Utilizing JQ to Filter JSON file by Utilizing Startswith while Implementing Case Insensitivity in the Search

Here is a sample JSON file that I am attempting to execute: { "$itemsPerPage": 1208, "$resources": [ { "$uuid": "7b44f5b6-a5bd-4c7a-8d4a-581ff36a1072", "$etag": "2016-08-12T12:29:33Z", "BPSNAM": "InfoCen ...

Leverage React components for efficient code reuse and export modules for

I have Project X, which was built using the command "yarn build" and it generated a main.js file. I am trying to use this main.js file as a dependency for another React project Y. Unfortunately, following the steps from React components and module exports ...

Attempting to refresh the choices in a dropdown list by sending a request via jQuery leads to specific

I have a Dropdown on my View that looks like this... <div class="editor-field"> @Html.DropDownListFor(model => model.CategoryId, new SelectList(new List<string>(), ""), "Select ...") </div> Within my controller, there is an action ...

What sets Babel and TypeScript apart from each other in terms of functionality and features?

While TypeScript was utilized to create Angular2, Babel also appears quite similar. Many established companies prefer Babel over TypeScript. Here are some questions to consider: What specific advantages does each one offer? Which is a better or worse ch ...

Testing post requests using Sinon.js, QUnit, and Jquery with FakeXMLHttpRequest validation

My QUnit test case is focused on checking the posted data sent via a JQuery ajax request: test("ajax tests", function () { var xhr = sinon.useFakeXMLHttpRequest(); var requests = sinon.requests = []; xhr.onCreate = function (request) { ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Using MappingJacksonValue with Spring Boot for JSONP response and handling strict MIME type errors

After extensively researching JSONP support with Spring 4, I am still struggling to find a straightforward explanation on how to make it work with the correct media type in Chrome. 1) I implemented the JsonpAdvice following the guidelines from Jackson JSO ...

TypeScript's Named Type Association

In my project, I have implemented a system that connects names to specific types through a Mapping Object Type called TMap The purpose of this system is to provide a handler function with information about one of the named types along with its correspondi ...

Tips for uploading an image to a server with JSON

Can someone please review my code and identify any errors? I am trying to upload an image to the server. The first time I upload a large image, it gives me a memory error. When I upload a small image afterwards, I can't seem to find where it's go ...