Understanding the basics of reading a JSON object in TypeScript

Displayed below is a basic JSON structure:

{
    "carousel": [],
    "column-headers": [{
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }, {
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }, {
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }]
}

I am looking to understand how I can interpret this JSON in Typescript. Ideally, I would like to handle it similar to how other high-level languages execute, by loading it and treating it as a dictionary for easy querying. However, if the only way to work with it is through serialization and deserialization techniques, I am comfortable with that approach as well.

Answer №1

When working with json data, Typescript and JavaScript are not inherently different.
If the json is received as a string, it needs to be parsed:

let json = JSON.parse(JSON_STRING);

After parsing, the data becomes a regular JavaScript object (assuming the json is an object {...}) that can be accessed like this:

let aHeader = json["column-headers][0];
let headerImage = aHeader.headerImage;

Typescript introduces the capability of defining the structure of this json data as a type:

interface ColumnHeader {
    header: string;
    text: string;
    headerImage: string;
    buttonText: string;
}

interface MyData {
    carousel: any[];
    "column-headers": ColumnHeader[];
}

let o = {
    "carousel": [],
    "column-headers": [{
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }, {
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }, {
        "header": "Heading",
        "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.",
        "headerImage": "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        "buttonText": "View details"
    }]
} as MyData;

let header = o["column-headers"][0]; // typeof header is ColumnHeader
let image = header.headerImage; // typeof image is string

(code in playground)

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

Substitute the colon in JavaScript prior to submitting the form

I am currently working on a text input search field where I want to automatically add an escape backslash to any colon entered by the user. Below is the code snippet I have implemented so far: <form role="form" action="..." method="get"> <div ...

Improving the retrieval of API data using personalized React hooks when searching by modifying keywords

I'm just starting out with React Hooks and recently wrote a small code snippet that displays a list of courses to users. This code includes two main components, CourseList and Course, as well as a custom hook called useCourseList. Here's the code ...

Python's request function is only retrieving a single element

Below is the code snippet I have: import base64 import requests import json import csv USERNAME, PASSWORD = 'Username', 'Password' req = requests.get( url="https://api.mysportsfeeds.com/v1.1/pull/nhl/2017-2018-regular/game_startin ...

Encountering a promise error when using TypeScript and React Lazy

I've been working with React and TypeScript, incorporating a higher order component to verify user authentication. However, after implementing the hoc, I encountered an error in my routes: /home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/rem ...

Utilizing dropbox.js in combination with OAuth 1: A step-by-step guide

I'm in the process of revamping a website that already exists, and although I have the code from the previous version, I'm encountering challenges replicating certain functionalities in the new iteration. Here's the situation: The user is ...

Check Image Dimensions prior to Image Loading

I've been working with JQuery Masonry and would like to incorporate Lazy Load using a WordPress plugin to load images only when they come into view. The issue I'm facing is that when Lazy Load is used, the masonry elements don't recognize t ...

How to properly handle special characters within JSON when using a data attribute

I have a JSON object stored in data attributes. <div data-dataarray="[[&quot;Shipper&quot;,&quot;Ship No&quot;,&quot;Weight&quot;],[&quot;1WWWQUICK\PARTSCOM&quot;,1,1]]"> data = $('#'+moduleId).data(&a ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Having trouble deserializing a JSON with an extended abstract class in Java using Jackson?

All the classes have been declared as static. The creation of objects occurs within the main() function provided below: import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson ...

Vite encounters issues when using PNPM because of import analysis on the `node_modules/.pnpm` package

When utilizing PNPM and Vite in a monorepo, I encountered a perplexing issue. The email addresses appearing like `<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b6a9b4a580f4eef4eef9">[email protected]</a>_@<a ...

Ways to retrieve a value within a function and update a variable

Fetching data from the firebase database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ console.log('Error!'); console.log(err); } function gotData(d ...

"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values. I am open to alternative method ...

Assigning a value to an Angular class variable within the subscribe method of an HTTP

Understanding the inner workings of this process has been a challenge for me. I've come across numerous articles that touch on this topic, but they all seem to emphasize the asynchronous nature of setting the class variable only when the callback is t ...

Saving modified input data for submission using Vue

Objective: The main goal is to have a form interface loaded with an object's current data for editing. This allows the user to open a modal with the form already filled out with the existing information, giving them the option to either edit it or lea ...

How can you determine the specific type of "display" utilized by CSS Bootstrap for a particular element?

When manipulating the "display" property of a bootstrap element like "row" or "col-md-3" using JavaScript, how can I determine the default value set by Bootstrap CSS? For instance, the Bootstrap source code likely sets the "display" value for the "row" cl ...

Can you display a popup on a leaflet map from beyond its boundaries?

Utilizing leaflet maps, I have implemented a functionality where clicking on the map opens a popup at a specified location and centers on that position. The code for this is as follows: var popup = L.popup(); function onMapClick(e) { popup . ...

JavaScript: What is the best method for eliminating all square brackets from within the outer array?

let list = [ ["water", "earth"], [6, "light"], [32], ["fire", "air", 9] ]; The example provided shows the list made up of four elements, each being an array. Currently, the length of list is 4. I am curious if there is a way to eliminate all inner square ...

How come AngularJS $onChanges isn't able to detect the modification in the array?

What is the reason behind Angular's failure to detect changes in an array, but successfully does so after changing it to null first? In my AngularJS component, I utilize a two-way data binding to pass an array. The parent component contains a button ...

Deviations in Scriptaculous Callbacks during Movement Effects

I am looking to create a dynamic menu item that moves out 5px on mouseover and returns to its original position using Scriptaculous. I have implemented the afterFinish callback to ensure that the bump-out effect is completed before the item moves back in. ...

Count duplicated values in an array of objects using JavaScript ES6

I am working on creating a filter for my list of products to count all producers and display them as follows: Apple (3) I have managed to eliminate duplicates from the array: ["Apple", "Apple", "Apple"] using this helpful link: Get all non-unique values ...