Converting JSON data into custom object types using TypeScript

Utilizing the AlphaVantage API, I am receiving a JSON response that looks like this:

{
    "Meta Data": {
        "1. Information": "Intraday (5min) open, high, low, close prices and volume",
        "2. Symbol": "IBM",
        "3. Last Refreshed": "2024-04-19 19:55:00",
        "4. Interval": "5min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (5min)": {
        "2024-04-19 19:55:00": {
            "1. open": "181.5200",
            "2. high": "181.5800",
            "3. low": "181.4600",
            "4. close": "181.5100",
            "5. volume": "158"
        },
        "2024-04-19 19:40:00": {
            "1. open": "181.2000",
            "2. high": "181.2000",
            "3. low": "181.2000",
            "4. close": "181.2000",
            "5. volume": "27"
        },
        "2024-04-19 19:30:00": {
            "1. open": "181.5600",
            "2. high": "181.5600",
            "3. low": "181.5600",
            "4. close": "181.5600",
            "5. volume": "20"
        },
        "2024-04-19 19:25:00": {
            "1. open": "181.5600",
            "2. high": "181.5600",
            "3. low": "181.5600",
            "4. close": "181.5600",
            "5. volume": "1"
        },...
    }
}

I am attempting to extract the data and save it in an object utilizing an interface:

type IntradayInterface = {
    metaData:          MetaData;
    interval: { [time: string]: IntervalData };
}

export type MetaData = {
    information:    string;
    symbol:         string;
    lastRefreshed:  Date;
    interval:       string;
    outputSize:     string;
    timeZone:       string;
}

export type IntervalData = {
    open:   string;
    high:   string;
    low:    string;
    close:  string;
    volume: string;
}

export default IntradayInterface;

Below is my parsing function:

function parseIntradayData(jsonData: any) : IntradayInterface {
    
    const metaData = jsonData['Meta Data'];

    let parsedMetaData : MetaData = {
        information: metaData['1. Information'],
        symbol: metaData['2. Symbol'],
        lastRefreshed: metaData['3. Last Refreshed'],
        interval: metaData['4. Interval'],
        outputSize: metaData['5. Output Size'],
        timeZone: metaData['6. Time Zone']
    };

    const intervalData = jsonData['Time Series (5min)'];

    let parsedIntervalData: IntervalData = {
        open: intervalData['1. open'],
        high: intervalData['2. high'],
        low: intervalData['3. low'],    
        close: intervalData['4. close'],
        volume: intervalData['5. volume']
    }

    const returnData: IntradayInterface = {
        metaData: parsedMetaData,
        interval: intervalData
    } 

    return returnData;
}
export default parseIntradayData;

The aim is to parse and store the data from the JSON response into an object of type IntradayInterface, but when attempting to do so, the object doesn't populate correctly. There are two assumptions on why this might be happening:

1 - The Interface may not be structured correctly, particularly with the interval definition. I want to include each datetime mapping to the corresponding IntervalData, but unsure how.

2 - The parsing of the "Time Series (5min)" section of the JSON may not be done correctly.

Support or guidance on this matter would be highly appreciated!

Answer №1

When dealing with the "Time Series (5min)" object in your input data, you may encounter nested objects that require transformation. To achieve this, an iteration over all these nested objects becomes necessary.

function parseIntradayData(jsonData: any) : IntradayInterface {
    
    const metaData = jsonData['Meta Data'];
    const parsedMetaData : MetaData = {
        information: metaData['1. Information'],
        symbol: metaData['2. Symbol'],
        lastRefreshed: metaData['3. Last Refreshed'],
        interval: metaData['4. Interval'],
        outputSize: metaData['5. Output Size'],
        timeZone: metaData['6. Time Zone']
    };

    const intervalData: Record<string, object> = jsonData['Time Series (5min)'];  //hint a type here, so
    const parsedIntervalData = Object.fromEntries(Object.entries<any>(intervalData).map(([k,v]) => {
      let t = {
        open: v['1. open'],
        high: v['2. high'],
        low: v['3. low'],    
        close: v['4. close'],
        volume: v['5. volume']
      };
      return [k, t];
    }));

    const returnData: IntradayInterface = {
        metaData: parsedMetaData,
        interval: parsedIntervalData
    } 

    return returnData;
}

Object.entries allows for the transformation of an object into an array of [key,value] pairs. This array can then be iterated over to transform the values accordingly. Finally, Object.fromEntries is used to convert the resulting [key,value] pairs back into an object.

For simplification when mapping the IntervalData, consider using:

let t = Object.fromEntries(Object.entries(v).map(([kk, vv]) => [kk, vv.split("" "")[1]])) as IntervalData;

This approach removes the prefix numbers from property names by splitting them on spaces and selecting the second element. A similar technique could potentially be applied to the MetaData object as well.

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

Obtain the closest numerical range using JavaScript

I have a range object and an array of price values. My goal is to find the nearest range from the range object for each value in the price values array. I attempted the solution below, but it did not give me the correct range. range = { 0: '25-500 ...

Unable to access ConnectWise API due to receiving an Invalid Token response

I have been attempting to access ConnectWise records through the ConnectWise API as shown in the images linked below: https://i.stack.imgur.com/ur9iW.png and https://i.stack.imgur.com/FPzBC.png However, each time I make a request, I receive an Invalid ...

Comparison of Saving JSON Data on Android: SQLite or SharedPreference

Looking to develop an application for members of my organization to access data on their mobile devices, I require a method to store pre-formatted data locally so it can be viewed offline. The data will be fetched using a JSON request-response. The respon ...

Is Angular capable of displaying a date within a specific timeframe using ng-show?

So I have a button that, when clicked, displays a list of data. I am adding a unique font awesome icon in there if the JSON key value exists. However, here lies the issue. The particular key happens to be a date. I need my ng-show function to check whether ...

Error encountered: React Typescript does not support the "any" type in a template literal expression

I have been encountering an issue with my slider component in React Typescript. The error message I keep getting is related to the "Invalid type 'any' of template literal expression" specifically at the const fillWidth variable. I am struggling t ...

Unable to concatenate string with API data in Python 3

I am currently using Python 3 to create a tool that interacts with an API. This particular API functions by sending http requests through URLs. The goal of my script is to scrape data from all the provided URLs and compile it into a single json file. Upon ...

Upgrading $compile in Angular

In my pursuit to compile HTML content in Angular 4, I have come across options like $compile in Angular 1. Unfortunately, the suggested alternatives in Angular 2 are now outdated. If anyone has a better approach, please advise me on the most effective wa ...

Retrieve data from a JSON array using either JavaScript or PHP

Check out my code snippet: const newData = [{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]; Now, I need to extract specific details from this JSON data based on the 'new_no& ...

How can I use JavaScript to retrieve information from a different webpage?

I am trying to extract data from another webpage using JavaScript, jQuery, or Ajax without using PHP. I came across a helpful example on Stack Overflow (link here). However, when I implement these codes in my index.html file, it doesn't seem to work. ...

Where does tsc retrieve its definitions from when utilizing npm definitions?

After transitioning from using typings to just relying on npm, I noticed that the @types directory in node_modules is present, but there are no additional files required. Previously with typings, I always had to include the index.d.ts file within the typi ...

The use of JSON format is not supported by the REST API method in [Java]

I am currently running tests on a REST API method in postman. The interesting thing is that when I perform the test using x-wwww-form-urlencoded, I receive the correct result, but when attempting it with the Json format, I encounter a status code of 500 - ...

Encountered a critical issue: Uncaught Error - Attempting to add data to JSON payload using an object of type stdClass

I am trying to add a new object to a JSON array using PHP. The JSON data is as follows: { "maxSize":"3000", "thumbSize":"800", "loginHistory":[ { "time": "1411053987", "location":"example-city" }, { "time": "14110 ...

Grouping Columns in an HTML Table using Angular 4

I'm currently faced with the task of retrieving flat data from an API and presenting it in an HTML table using Angular 4. I'm a bit unsure about how to iterate over the data, possibly using a for-each loop. I have attempted to utilize ngFor but I ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

Displaying jsp variable in the browser console

When working in JSP, using <p>${ob}</p> to retrieve an object can be challenging due to the size of the object. Is there a way to utilize JavaScript to print it instead? Keep in mind that since this involves handling email content, JavaScript ...

Transform JSON data that illustrates an array into an array of strings

There is an external string that represents a JSON array. Here's how it looks: ["abc", "xyz", "123"] The goal is to parse this into a String[] and then iterate over its elements. Currently, the code snippet outlines the intention of using the parse ...

Tips for maintaining the menu state following a refresh

Is there a way to save the menu state when pressing F5? I'm looking for a similar functionality as seen on the Binance website. For example, clicking on the Sell NFT's submenu and then refreshing the page with F5 should maintain the menu state on ...

IntelliJ does not provide alerts for return type inconsistencies in TypeScript

During the development of our web application using react+typescript+spring boot with IntelliJ, everything seemed to be going smoothly until I came across an unexpected issue. Take a look at this code snippet example: export class TreeRefreshOutcome { } e ...

The extremely lengthy JSON reply pauses abruptly to transmit HTTP headers in plain text before resuming

I am completely lost on this issue. My ajax query retrieves a json response. The query usually works fine, but it seems to encounter difficulties when the json response is very large. The problem arises when the response looks like this: ...est":"test l ...

Guide to making a custom type by extending a union type in TypeScript

Looking to define a new structure here type DataTableCol<T, K extends keyof T> = { title: string; key: K; render?: (value: T[K]) => ReactElement; }; In need of creating a type called DataTableRow<T> based on the above. For instance, w ...