Working with Typescript: Learning how to import and retrieve data from JSON files with dynamic

Currently, I am facing an issue while attempting to import a JSON file that contains keys with unknown values (such as device names) in TypeScript. I am struggling to access the imported data with variable keys at runtime.

For example, consider the following JSON file named "test.json":

{
    "a": {
        "b": "1"
    }
}

Here is a snippet of TypeScript code for reference:

import t from "./test.json";

let k = "a"          // <- variable key

console.log(t["a"]); // <- ok
console.log(t[k]);   // <- error

The TypeScript error message displayed is as follows: The element implicitly possesses an 'any' type because the expression of type 'string' cannot be used to index type '{ a: { b: string; }; }'. No index signature with a parameter of type 'string' was found on type '{ a: { b: string; }; }'.

I have done some research on TypeScript Records and Index Signatures, but I am unsure how to effectively import or "cast" the JSON data so that it can be accessed using variable keys. It is important that the data is validated at runtime.

Answer №1

Here is a solution that should function properly. Interactive Playground

  const json = { "a": { "b": "1" }, "c": {"d": "1"} }; // <-- simulate import

  type Unsafe = { [parentKey: string]: {[childKey: string]: any} } ;
  // key not tpyed
  let k = "a"

  const t: Unsafe = json;
  console.log(t["a"]); 
  console.log(t[k]);   // <- ok but could fail on runtime

  // safe approch
  type Safe =Record<'a'| 'c', {[key: string]: string}>
  // typed key
  let saveKey: keyof Safe = "a"          // <- variable key
  
  const safe: Safe  = json;
  console.log(safe['a'])
  console.log(safe[saveKey])
  

Answer №2

It appears to be functioning as expected

const obj = {
    "key1": {
        "subKey": "value1"
    }
}
type ObjectKeys = keyof typeof obj;
let key: ObjectKeys = "key1"; 

console.log(obj["key1"]); 
console.log(obj[key]);   

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

Detecting Typescript linting issues in VSCode using Yarn version 3.2.3

Every time I try to set up a new react or next app using the latest yarn v3.2.3, my VS Code keeps showing linting errors as seen in the screenshot below. The main error it displays is ts(2307), which says Cannot find module 'next' or its correspo ...

What is the correct way to execute a POST request?

Currently tackling a basic API project. Managed to nail the GET & DELETE requests, but the POST request is giving me a hard time. I'm almost positive it's a beginner mistake, but I can't seem to figure out the logic here. This specific file ...

Tips for resolving Circular dependency issue in node.js?

While working on a post request, I encountered an issue with the code below: try{ const _id = await db.collection('UserInformation').insertOne(userObj); await db.collection('LoggedInUser').updateOne({ userId: _id }, { '$set&ap ...

The function json.stringify fails to invoke the toJson method on every object nested within the main object

When using IE 11, I encountered an issue where calling Stringify on my objects did not recursively call toJson on all objects in the tree. I have implemented a custom toJson function. Object.prototype.toJSON = function() { if (!(this.constructor.name == ...

The VueJS function is not defined

Looking for a way to fetch data from graphql in my vue project and store it in a variable. The function is asynchronous and the value of rawID needs to be awaited. However, there is a possibility that it could result in undefined, causing an error in the ...

Implementing the "module": "ES2020" configuration in a Node.js project instead of using commonJS

Is there a way to implement ES2020 in tsconfig instead of commonjs for a Node.js project? I've noticed that when using commonjs in TypeScript, the compiled output results in a large amount of JavaScript files. ...

Using the `json_normalize()` function within the pandas library allows

Python version: 2.7 I'm currently working on normalizing JSON data stored in MongoDB using json_normalize. However, I am facing an issue with flattening the data within the "stages" element as it is appearing within the collection instead. Processing ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

Attempting to fill a collection of JSON entities through a GET call?

When handling a GET request that contains a list of JSON objects, I want to display the data in an input field on the screen using ng-model for data binding. The structure of the JSON get request is as follows: [{"make":"Mahindra","vin":"1987","model":"XU ...

Transforming JSON date format to a different one using Jackson libraries

My spring boot 1.3.5 application is using jackson with the dependency "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.5.0". Encountering an issue when a user inputs a date value in a format different than expected (mm/dd/yyyy) during a POST requ ...

Tips for effectively navigating with the `Next-intl` and `next/link` componentsWhen working with the

I have implemented a next-intl library to enable multi-language support on my website. This means that the paths for different languages look like www.next.com/de or www.next.com/en Currently, I am utilizing NextJS 14. <NextLink href="/support-us& ...

Navigate Formik Fields on a Map

Material UI text-fields are being used and validated with Formik. I am looking for a way to map items to avoid repetitive typing, but encountering difficulties in doing so. return ( <div> <Formik initialValues={{ email: '&a ...

Transforming JSON into Java objects with the help of Google's Gson technology

I am utilizing Spring Social FqlQuery to retrieve data from Facebook. The JSON response received from Facebook is displayed below. Here is the controller where I fetch the JSON output: fql = "SELECT work FROM user WHERE uid = me()"; facebook.fqlOperations ...

Retrieve an object that includes a property with an array of objects by filtering it with an array of strings

I have a large JSON file filled with data on over 300 different types of drinks, including their ingredients, names, and instructions. Each object in the file represents a unique drink recipe. Here is an example of how one of these objects is structured: ...

Navigating through JSON object fields within Angular component [Version 11]

Check out this Angular service method that calls a basic REST API: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Token } from './Token'; import { map } fro ...

Retrieving essential information from a JSON file using a model class approach in Python

When dealing with an input Json data structure, it is essential to extract only certain key fields like ID, CommonTags, and Value. One common approach to achieve this is by using for loops to iterate over the data and fetch and store the required values. ...

Angular 10: Module Alias Import Not Resolving in VSCode due to Path Mapping Recognition Issue

After updating a project from Angular 8.2 to version 10, I followed the instructions on https://update.angular.io/ and everything seemed fine. However, once I implemented Path Mapping, I started encountering this error everywhere: Cannot find module ' ...

Issue with TypeORM custom repository not successfully overriding the createQueryBuilder function

I have successfully implemented database i18n for TypeORM in theory. Now, I am looking to override built-in repository methods to incorporate i18n by intercepting them and adding a query. However, I am facing difficulties with overriding the createQueryBui ...

Transmitting a sequence of JSON information from php to JavaScript,

I am struggling to fetch a series of JSON data from PHP to my JavaScript file. Initially, I have multiple JSON data stored in an array in PHP, and I am echoing each one by looping through the array in my JavaScript file. <?php $result = array('{ ...

Combining two JSON arrays to create a unified format

Details of the First Array {categories":[{"label":"2018-05-24T12:04:01.000Z"},{"label":"2018-05-24T12:05:03.000Z"},{"label":"2018-05-24T12:08:08.000Z"},{"label":"2018-05-24T12:09:10.000Z"},{"label":"2018-05-24T12:11:14.000Z"},{"label":"2018-05-24T12:12:1 ...