0
votes

Getting below error message while trying to read a description attribute from below Sample Json.

Error: TypeError: Cannot read property 'description' of undefined while reading json data to 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"
   ]
}
1
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"] } - Tej Kumar
sample.json export interface Age { description: string; type: string; minimum: number; } - Tej Kumar
use JSON.parse like here let obj = JSON.parse(jsonString); - Rahul Hendawe

1 Answers

1
votes

Here is a working StackBlitz.

Since this is Typescript the trick is cast the json as the type needed. Since sample.json is more than the Age interface listed in the comments, we'll create a new interface, called PersonSchema.

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

Now we can import the json data. Note: import {Age} from "./sample" does not work because the sample file is json and cannot export a type.

import data from './sample.json';

Cast it as the type needed:

const person = data as PersonSchema;

Access the age:

const age = person.properties.age;