Issue: An error occurred while trying to parse JSON data in TypeScript due to an undefined 'description' property

Encountering an error message when attempting to retrieve the description attribute from the following Sample Json.

Error: TypeError: Cannot read property 'description' of undefined when trying to access json data in typescript

import {Age} from "./sample" 
var a:Age;    
console.log(a.description);

Sample.json :

{
   "title":"Example Schema",
   "type":"object",
   "properties":{
      "firstName":{
         "type":"string"
      },
      "lastName":{
         "type":"string"
      },
      "age":{
         "description":"Age in years",
         "type":"integer",
         "minimum":0
      },
      "hairColor":{
         "enum":[
            "black",
            "brown",
            "blue"
         ],
         "type":"string"
      }
   },
   "additionalProperties":false,
   "required":[
      "firstName",
      "lastName"
   ]
}

Answer №1

Check out this StackBlitz link for a working example.

In Typescript, the key is to cast the json data to the required type. If the data in sample.json is more complex than just the Age interface mentioned in the comments, a new interface called PersonSchema needs to be created.

interface PersonSchema {
  title: string;
  properties: {
    age: Age;
  };
}

Next step is to import the json data. Importing {Age} from "./sample" won't work because a JSON file cannot export a type.

import data from './sample.json';

Cast the data to the required type:

const person = data as PersonSchema;

Now you can access the age property:

const age = person.properties.age;

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

Storing and Retrieving User Identifiers in Next.js

Currently, I am developing a project using Next.js and I have the requirement to securely store the userId once a user logs in. This unique identifier is crucial for accessing personalized user data and creating dynamic URLs for the user profile menu. The ...

Is it possible to locate a specific string within a JSON object?

I need to locate Fortnite and retrieve the app version and file path of fortnites. The challenge is that I do not know if the user has other apps installed, how many there are, or what they are. My goal is to accomplish this task using C#. I have attempt ...

What's causing the IndentationError in my Python code?

import requests import json url='https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY' headers= {'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36&ap ...

Error encountered when attempting to utilize ngTemplate to embed filter within a table

I am facing an issue with a component that includes a primeng table. Within a table row, I have an ng-container to project a p-columnFilter into the table from an external source. However, when trying to pass the filter into the template, I encounter a Nul ...

What is the best way to deserialize nested JSON data with Spring RestTemplate?

After following the guide on consuming RESTful Web Services from the Spring website, I realized it did not cover the topic of deserializing nested objects. How would one go about deserializing the location entry in the provided sample? ...

The value of the JSON object is empty

I am facing an issue with the code below that is supposed to read data from a JSON file containing rules and display it on the UI. However, when I run the code, I get the following output: Technology: null Vulnerability: null Severity: null RegEx: null D ...

HTTP Interceptor never finishes executing (finalization is never triggered)

In my angular 8 project, I created a basic HttpInterceptor that simply duplicates the original request and includes an additional parameter: @Injectable() export class RequestHeadersInterceptor implements HttpInterceptor { intercept(request: HttpReques ...

Generate an li element that is interactive, containing both text and a span element

I am dealing with a JSON array that looks like this: var teamDetails=[ { "pType" : "Search Engines", "count" : 5}, { "pType" : "Content Server", "count" : 1}, { "pType" : "Search Engines", "count" : 1}, { "pType" : "Business", "count" : 1,}, { "pTyp ...

Ajax encounters difficulty in parsing JSON data

I have thoroughly researched similar questions on this topic, but none of them have provided a solution to my problem. My current challenge involves parsing JSON data that is being returned from a PHP script running on the server. I have already used JSON ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

Using Angular to share JSON data efficiently between controllers

Greetings everyone, I am a beginner in Angular and not very skilled with JavaScript. The issue I'm facing is that although this setup successfully fetches the JSON data, whenever I modify certain object properties, they revert back to their original s ...

Combining pixijs with TypeScript in Ionic 2 using npm

To begin, I ran the command npm install -g ionic Followed by ionic start pixiApp blank --v2 Navigated to the pixiApp directory with cd pixiApp Installed necessary dependencies using npm install Added a specific version of pixi.js (4.1.0) with npm install p ...

React Redux not properly handling text input updates when onChange event is triggered

I have come across similar inquiries, but they haven't provided the solution I need. Currently, I am working on a React project where I am integrating redux. This is how my index.js looks: import React from "react"; import ReactDOM from "react-dom"; ...

The tsconfig within the module directory fails to supersede the extended tsconfig properties present in the parent directory

Within the directory store/aisle/fruits, there is a tsconfig.json file: { "compileOnSave": true, "compilerOptions": { . . "target": "es6", "noEmitOnError" : true, "noEmitHelpers ...

There is no matching overload for this call in Angular. Error code: TS2769

Having trouble identifying the issue in this TypeScript code snippet. Error reported on line 5, ".subscribe((response: { Token: string }) => {". login() { this.httpClient .post('http://localhost:4000/signin', this.loginForm.value) ...

Why isn't my jQuery Flot Pie chart functioning properly when using $.Ajax and JSON?

I'm attempting to use JSON to generate a flot pie chart. It works perfectly with static data, but when I try to send data dynamically using JSON, nothing is displayed. Check out my code below: <script src="jquery-1.11.2.min.js"></script> ...

Transmitting an HTML file along with JSON data and enabling the browser to refresh the JSON data without reloading the entire

I'm currently working on a project involving a browser-server program where the browser sends an http get request to ''. The server is expected to return both an HTML page and a JSON response. I attempted using res.render(), passing the JSON ...

The functionality of the Ionic 4 app differs from that of an Electron app

I've encountered an issue with my Ionic 4 capacitor app. While it functions properly on Android studio, I'm having trouble getting it to work on Electron. Any ideas on how to resolve this? Here are the steps I took to convert it to Electron: np ...

Using Swift to populate a UITableView with image URLs from JSON data

As a beginner in Swift programming, I have been working on downloading Json data as Strings and displaying them in a UITableView with image url links. However, I encountered a problem due to the large amount of data, specifically 53, which results in 53 ur ...