Utilizing TypeScript to parse a JSON document

As a complete beginner in learning TypeScript, I am exploring how to parse JSON data on a web page and understand the underlying process. Despite searching extensively online, I have yet to find a solution.
Here is my current code:

var a = fetch("places.json")
  .then(response => response.json())
  .then(json => console.log("json"));
//The above line prints the JSON data to the console

Below is the content of places.json


{
  "html_attributions" : [],
  "results" : [
     {
        "formatted_address" : "123 Main St, Boston, MA 02110, USA",
        "geometry" : {
           "location" : {
              "lat" : 42.3744875,
              "lng" : -71.06347439999999
           },
           "viewport" : {
              "northeast" : {
                 "lat" : 42.37581182989273,
                 "lng" : -71.06218627010728
              },
              "southwest" : {
                 "lat" : 42.37311217010728,
                 "lng" : -71.06488592989272
              }
           }
        },
        "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
        "id" : "4747c342bc144e98fba53bf2f41b6ed707e2fef0",
        "name" : "123 Main St",
        "place_id" : "ChIJd_ueCe1w44kRD_KFuN5w5nA",
        "plus_code" : {
           "compound_code" : "9WFP+QJ Boston, Massachusetts, United States",
           "global_code" : "87JC9WFP+QJ"
        },
        "reference" : "ChIJd_ueCe1w44kRD_KFuN5w5nA",
        "types" : [ "street_address" ]
     }
  ],
  "status" : "OK"
}

Answer №1

If you're familiar with the JSON format in advance and prefer using TypeScript instead of JavaScript, one approach is to define an interface or type that matches the structure of the JSON data and then simply cast it like this:

interface Locations {
  html_info: Array<any>,
  entries: Array<object>,
  status: string
}

const parsedData: Locations = <Locations>a;
console.log(parsedData.status);
// This will output the status

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

Trying to access the 'cpf' property of an undefined value is causing an error

I have a file that I'm using to create an object to store in my Firestore database. The file is imported into my register page, and I'm using ngModels to capture user-input values. To achieve this, I've initialized my data object inside the ...

Interacting with child collections data in C# through a RESTful API using Entity Framework context

Utilizing projection (explicit loading) to fetch and filter collection data from a child table via a RESTful Api service results in the JSON repeating the child table collections object. However, using the "AsNoTracking()" method eliminates the nested chil ...

Error message in TypeScript React: Unable to assign onClick to type 'IntrinsicAttributes'

I recently came across this code for a component: Feedback.tsx import React, { useState } from 'react'; import './Feedback.css'; import FeedbackButton from './FeedbackButton'; function Feedback() { const [isOpen, setIsOpe ...

Retrieve and extract JSON data from the GDAX API

Attempting to retrieve the BTC-EUR ticker from GDAX site and transfer it to Google Spreadsheet using a script has proven challenging. Despite following this code, an error consistently arises: The coordinates or dimensions of the range are invalid. var ...

What steps are involved in creating a local unleash client for feature flagging?

Currently attempting to implement a feature flag for a Typescript project using code from the Unleash Client. Here is where I am creating and connecting to an instance of unleash with a local unleash setup as outlined in this documentation: Unleash GitHub ...

Access information from deeply nested JSON objects and present it in a formatted list using AngularJS

Currently, I am facing a challenge while working on an AngularJS app that utilizes JSON data. As a beginner with Angular, I encountered a point of confusion. Here is the issue: Below is the snippet from the controller: courseController.controller('L ...

Navigating through a JSON data structure

The information retrieved from the PHP page appears as follows: [{ "id": "1", "name": null, "startdate": "2012-07-20", "starttime": "09:53:02", "enddate": "2012-07-20", "endtime": "09:54:10", "duration": "01:00:00", "feedba ...

Typescript claims that my object lacks certain properties that it actually has

I'm currently developing a project that follows this particular structure: interface IAuthProvider { middleware: () => void getInput: () => void } class Password implements IAuthProvider { middleware = () => {} getInput = () => {} ...

OECD API generates an exclusive Vega-Lite visualization

I'm trying to incorporate an API directly into Vegalite for automatic chart updates. Here is the link to the API: API Link However, the format of the API data is not user-friendly. { "$schema": "https://vega.github.io/schema/vega-lit ...

Troubles with Angular2 template parser when parsing HTML fragment that is W3C validated

The online W3C validator successfully parses the following document: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>test</title> </head&g ...

"Exploring How to Read Multiple Values in the Request Body Using Node.js

I am new to NodeJs development and have a question. It may be basic, but I'm not sure how to proceed. I have a task to read a request field that can contain multiple values in a JSON array like this: { "email" : "<a href="/cdn-cgi/l/email-prote ...

Iterating through a JSON object with a mix of dictionaries and lists in Python

{'PCCandidateDetails': {'BatchId': '456279', 'Candidate': 'Noori sahi ', 'CandidateId': '9124657', 'CenterName': 'K', 'ProjectName': 'PKKVY&apo ...

I'm curious, what is the optimal method for arranging a json object based on an index contained in each of its properties?

I'm working with an array of objects, looking like this myArray = [ { id: 3, data: foo }, { id: 7, data: bar } ] However, I would like to transform it into the following structure transformedArray = { 3: ...

The Nodejs page becomes unresponsive when making several requests to a Custom API

My application encounters a problem where it only works smoothly when I submit the form once. If I try to press the Submit button multiple times, the application freezes for some time (around 1000.000 ms) before returning the last request in the console an ...

Tips for generating a fresh JSON object utilizing a dictionary in Python

What is the most efficient method for creating a new dictionary in Python based on existing attributes from another dictionary? Consider the following example where we have the initial dictionary: dict1 = { "name": "Juan", "lastname": "Gonzalez", "swimmin ...

Ways to ensure that all information within nested arrays is completely and clearly displayed in JSON format

I have a Function that generates a JSON: Function New-JSONTest { Param ( [Parameter( ParameterSetName = "NewConfig" )] [switch]$NewConfig ) $PSCustomObject = switch ($PSCmdLet.ParameterSetName) { NewConfig { ...

Implementing Global Value Assignment Post Angular Service Subscription

Is there a way to globally assign a value outside of a method within my app component? This is how my service is structured: import { NumberInput } from '@angular/cdk/coercion'; import { HttpClient } from '@angular/common/http'; import ...

Encoding data in JSON format using C# Core

I'm just starting to delve into JSON serialization. Scenario: I've initiated a call to a REST API in order to retrieve information. My goal is to extract data from the API and use it for calculations. However, I seem to be facing some issues wit ...

Converting hexadecimal literal strings to integers using C# and Json

I'm a bit stuck and confusing myself, really. I'm trying to convert a value from a JSON string, specifically from its string representation of hex to an integer. I only need to extract the value and won't need to convert it back. For exampl ...

Enhancing .gitignore with conditional logic for more efficient file exclusion

In my TypeScript project, I am facing an issue with unnecessary merge conflicts caused by the generated .d.ts and .js files. Since my project is quite large and only halfway converted from JS to TS, I cannot simply ignore all .js files using .gitignore. A ...