Guide to creating a type for a JSON object with nested properties in TypeScript

I have some JSON strings structured as follows:

{
    name: 'test',
    url: 'http://test.org',
    contact: {
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0263636342766771762c616d6f">[email protected]</a>',
        address: 'ab road'
    }
}

My goal is to define a type for this data, so I attempted the following:

type Site = {
    name: String,
    url: String,
    contact: {
        email: String,
        address: String
    }
};

However, I encountered an error message stating:

Unexpected token n in JSON at position 15

As I am not well-versed with TypeScript, I wonder if it is feasible to define types in such a nested manner that closely mirrors the structure of the actual JSON. Is this achievable? If so, what is the correct approach to defining it?

Answer №1

Your type definition appears to be correct. However, the issue lies in the formatting of your JSON data. Make sure to use double quotes for property names and string values:

{
    "name": "test",
    "url": "http://test.org",
    "contact": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddbcbcbc9da9b8aea9f3beb2b0">[email protected]</a>",
        "address": "ab road"
    }
}

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

Retrieving a particular value from a JSON array using SQL syntax

Imagine having a table column filled with person data stored in a JSON array format, complete with categories and names. With SQL, it is possible to retrieve the information for a specific element in the array effortlessly: SELECT JSON_VALUE('{ " ...

Save the current date and time within a data structure in a CouchDB database

When trying to save sensor data on a Raspberry Pi in CouchDB using the pycouchdb library, I decided to create a database model class for a more organized structure instead of using loosely typed dictionaries. class SensorMeasure(NamedTuple): temp: fl ...

Angular: How can the dropdown arrow in 'ng-select' be eliminated?

Is there a way to hide the dropdown arrow in an 'ng-select' element in Angular? <div class="col-md-6"> <ng-select id="selectServiceType" [items]="clientServiceTypes$ | async" pl ...

"Looking to personalize marker clusters using ngx-leaflet.markercluster? Let's explore some ways to customize

I am currently struggling to implement custom cluster options in ngx-leaflet. My goal is simply to change all marker clusters to display the word "hello". The demo available at https://github.com/Asymmetrik/ngx-leaflet-markercluster/tree/master/src/demo/a ...

Storing JSON data in a SQL database

Storing JSON in an MsSql database and passing it to Javascript via a PHP script has been working perfectly. However, when trying to include extra text that is not part of the formatting string, like d, h, a, or p characters, encountered some challenges. Lu ...

React Native error - Numeric literals cannot be followed by identifiers directly

I encountered an issue while utilizing a data file for mapping over in a React Native component. The error message displayed is as follows: The error states: "No identifiers allowed directly after numeric literal." File processed with loaders: "../. ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

Dynamically loading JSON information into a DIV using AJAX requests

I have a list of Events in JSON format that I want to display. Below is the JSON data: [{ "event_id": "1636", "event_name": "Nitelounge supported by Mo\u00ebt &amp; Chandon", "event_start_date": "2013-05-27", "event_start_time": " ...

Hold on until the page is reloaded: React

My current setup includes a React Component that contains a button. When this button is clicked, a sidePane is opened. What I want to achieve is refreshing the page first, waiting until it's completely refreshed, and then opening the sidepane. Below i ...

DuplicateModelError: Unable to duplicate model after it has been compiled, React.js, MongoDB, TypeScript

In the early stages of developing an application using Next.js, Mongoose, and Typescript, I encountered a persistent issue. Whenever I attempt to send a request through Postman after clicking save, it fails, displaying the error message: OverwriteModelErr ...

Retrieving Ajax Json Data: A Guide on Accessing the Response Data

Upon clicking on the listproduct button, a collapsible table will be displayed featuring products that correspond to the specific invoice number. In my View File: <script> $(document).ready(function(){ $(".listproduct").click(function(){ ...

creating a personalized JSON response format in Go

Using the "encoding/json" package, I am able to output in JSON format. However, I want to customize the response structure. Below is a snippet of the code: var people []Person people = append(people, Person{Id: "1", Firstname: "John", Lastname: "Doe", Add ...

Typescript error: the argument passed as type a cannot be assigned to the parameter of type b

In my programming interface, I have defined shapes as follows: type Shape = | Triangle | Rectangle; interface Triangle {...} interface Rectangle {...} function operateFunc(func: (shape: Shape) => void) {...} function testFunction() { const rectFun ...

What is the reason behind the angular http client's inability to detect plain text responses?

When I make a call to httpClient.get, I notice in Fiddler that both the request and response headers have text/plain format. Request: Accept: application/json, text/plain, */* Response: Content-Type: text/plain; charset=utf-8 Even though I am returning a ...

Optimal approach to configuring Spring Boot and Angular for seamless communication with Facebook Marketing API

Currently, I am working on a Spring Boot backend application and incorporating the Facebook marketing SDK. For the frontend, I am utilizing Angular 10. Whenever I create a new page or campaign, my goal is to send the corresponding object back to the fronte ...

JSON failing to show all values sent as a string

In a div element there is a table with 3 rows, a textarea, and a button. The JSON data populates the first 3 rows correctly but the textarea remains blank. My goal is to display the previous record from the database in the textarea. function ChangeLoadin ...

Unlocking the secret to accessing keys from an unidentified data type in TypeScript

The code snippet above will not compile due to an error with the email protection link. const foo: unknown = {bar: 'baz'} if (foo && typeof foo === 'object' && 'bar' in foo) { console.log(foo.bar) } An erro ...

The issue with Angular 2's router.navigate not functioning as expected within a nested JavaScript function

Consider the app module: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angul ...

Attempting to decode an array of objects in Golang using the Unmarshal function

Hello, I am having trouble unmarshaling the value of an array inside a JSON field. When I try to access the array, it returns as empty and I'm not sure why. Can anyone please help me troubleshoot? Here is the code snippet: package main import ( " ...

The functionality of the System JS map is not functioning properly

Despite the challenges I face with System.js, I find it to be a valuable tool that I prefer over alternatives. This is my current System.js configuration: System.config({ packages: { app: { format: 'register' ...