I have to deserialize a C# dictionary serialized in JSON and integrate it into my Angular 6 website using TypeScript

Utilizing an API, I receive a JSON string that I aim to deserialize within my Angular 6 website.

Due to my unfamiliarity with how dictionaries function in TypeScript, I tend to steer clear of them when dealing with API responses.

Upon executing the following code:

console.log(JSON.parse(viewed_availab));

The output appears as follows:

[{
    "2019-05-10T00:00:00": {
        "TotalStopsCount": null,
        "TotalRoutesCount": null,
        "TotalStopsCountAfterBooking": null,
        "OccupancyRate": null,
        "OccupancyRateAfterBokking": null,
        "ZoneId": null,
        "DomainName": "MTH",
        "Date": "2019-05-10T00:00:00",
        "IsAvailable": false,
        "Status": {
            "Message": "Not enough time for items to reach final destination",
            "StatusID": 1
        },
        "IdDomains": null,
        "Items": []
    }
}]

This is the request I make to obtain the aforementioned string:

this.dataService.post('cleard.api.timeslot.viewed_availabilities', new ViewedAvailabilityParams(search.postalCode, search.userName, search.date, search.businessUnitId, search.originLocationId))
.then((viewed_availab: string) => {
...
    }).catch((error) => { this.searching = false; });

To better structure the response, I am aiming for a TypeScript dictionary format:

Dictionary<Date, Availibility> // shown in TypeScript syntax.

In this setup, the date serves as the key (taken from the first line of the Json), while availability represents the corresponding data:

{"TotalStopsCount": null,
"TotalRoutesCount": null,
"TotalStopsCountAfterBooking": null,
"OccupancyRate": null,
... and so forth }

(Note: A model has already been created for Availability).

Answer №1

In Typescript and Javascript, a dictionary is essentially just an object. You can easily loop through its key-value pairs using the method Object.entries:

const dictionary = {
  'key1': value1,
  'key2': value2
};

Object.entries(dictionary).forEach(([key, value]) => {
  // ...
});

Suitable types that can be used are: Record<TKey, TValue>, { [key: string]: T }

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

Is combining a string and a React element within the same array considered acceptable in the world of React?

Consider a scenario where you need to display data in the form of string[][]. Here is the code snippet: export interface IProps { correctAnswers: string[][]; } public render(): JSX.Element { return ( <div> {this.props.c ...

Encountered a null value when executing methods for the second time in an Angular application

I am facing an intriguing issue with a fragment of my app's code. CategoriesPageComponent: export class CategoriesPageComponent implements OnInit { private categories: Array<Category> = []; public randomizedCategories: Array<Category&g ...

Is it possible for one component to access the viewmodel of another component that is not related?

I am working with Typescript, React, and Material-UI. I'm using plain React without Redux or Flux. My goal is to scroll to the TabsComponent and select a specific tab when a button in the ButtonComponent is clicked. These components are not directly ...

How to incorporate a JSON schema as an array in PHP

In my PHP code, I am attempting to insert a new key and its corresponding content into a JSON file. $content = file_get_contents($_POST["content"]); $decode = json_decode($content,true); $version = $_POST["version"]; array_unshift($decode['versions&a ...

Guide on integrating ng-container and ng-content (with select tag) in Angular version 4

Can you provide an example of using ng-container along with ng-content containing a select tag? <div class="container"> <div id="first"> <ng-container *ngTemplateOutlet="widgetContent"></ng-container> <div> <di ...

Find the specific size of an HTML element

How can you retrieve an element's dimensions while avoiding CSS properties that take up unnecessary space? For example: <!DOCTYPE html> <html> <head> <style> #foo { height: 48px; margin: 64px; ...

I am attempting to develop a button that will navigate me to the SettingsScreen.tsx 'section'

I'm encountering persistent errors no matter how I approach it. (Apologies for the slightly messy code) import React, { useEffect, useState } from "react"; import { View, Text, StyleSheet, Image, Animated, Switch, TouchableOpacity, Button, ...

Why do I keep encountering the error "global is not defined" when using Angular with amazon-cognito-identity-js?

To start, run these commands in the command line: ng new sandbox cd .\sandbox\ ng serve Now, navigate to http://localhost:4200/. The application should be up and running. npm install --save amazon-cognito-identity-js In the file \src&bso ...

Is there a way to preserve the original index signature of an object while also defining the type of its values?

I have a large object containing various animals with different characteristics. I'm looking to properly type this object in TypeScript. interface Animal { legs: 0 | 1 | 2 | 3 | 4; } const Animals: Record<string, Animal> = { snake: { le ...

Utilizing Python to Insert JSON Objects into Postgresql

When attempting to import JSON Data into Postgresql using Python, a "psycopg2.ProgrammingError: can't adapt type 'dict'" error occurs when the "via" field with a JSONB data type is included in the created table in the Postgresql Database. Is ...

The Observable type of unknown cannot be directly assigned to Observable type of {}. In order to be compatible, the unknown type must have properties such as name, email, and isAdmin

My function is designed to return an observable containing a generic object. If the user exists, it returns the user object, otherwise it returns null. However, I am encountering an error that states: observable<-unknown-> is not assigned to obser ...

Having trouble establishing a connection with the SQL Server through my VS Code extension in node.js

Currently working on a VS Code extension and facing challenges in retrieving data from an SQL Server database. Despite trying multiple examples, none of them seem to be effective for me. const Connection = require('tedious').Connection; ...

Clicking on hyperlink within email to open in default web browser

I am facing a problem with my Angular web app. Here is the scenario of the issue: When I send a link to my app via email and try to open it from a mobile email client using a short version of a browser or webview (not sure what it's called), I encou ...

What is the correct way to log a complex object using Serilog so that it is formatted in valid

Presented is the structure below: public class LogRequestParameters { public string RequestID { get; set; } public string Type { get; set; } public string Level { get; set; } public string DateTime { get; set; } public string Machi ...

Having trouble with jQuery.cookie saving my JSON data

Being new to jQuery and JSON, I find this situation quite frustrating as it seems pretty straightforward but still doesn't work for me. My ASP.NET MVC website is using AJAX (via jQuery) to load data. Everything works fine until this point. I'm ...

Capturing a webpage through Record RTC integration with Angular

I am looking to record a specific section of the page as a video with audio. For example, when a user enters the page, I want it to automatically start recording the activities in that particular area (similar to how iframe videos work). The recording sh ...

Implementing Generic Redux Actions in Typescript with Iterable Types

Resolved: I made a mistake by trying to deconstruct an object in Object.assign instead of just passing the object. Thanks to the assistance from @Eldar and @Akxe, I was able to see my error in the comments. Issue: I'm facing a problem with creating a ...

Issue with Angular2 discount calculation formula malfunctioning

I'm encountering a rather perplexing issue with Angular2/Typescript. My goal is to compute the final price based on a specified discount value. Here's the formula I am using: row.priceList = row.pricePurchase + (row.pricePurchase * row.markUp / ...

React enforces a restriction on importing types from external directories when using TypeScript in the project

I'm facing an issue in my React project that is built with TypeScript. I am attempting to import types from a directory located outside of the React folder, but for some reason, React is not allowing this. I have integrated craco on top of Create Reac ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...