Working with JSON data in Angular components written in Typescript

Here is a snippet of my json data:

{
"Temp": [
    {
        "dt": 1485717216,
        "temp":30,
        "time":"05:17:55 PM"
    }
]
}

By parsing the above json, I can extract the temperature and time values using Angular -

ngOnInit() {
this._weather.dailyForecast()
  .subscribe(data => {

    let temp = data['Temp'].map(data => data.temp)
    let time = data['Temp'].map(data => data.time)
  }
}

However, I am encountering difficulties when trying to parse the following json data-

{
    "temp":30,
    "time":"05:17:55 PM"
}

Could someone please advise me on how to parse this json data?

Updated code: Service code

export class WeatherService {

constructor(private _http: HttpClient) { }

dailyForecast() {
return this._http.get("----url----")
  .map(response => response);
}
}

Answer №1

It seems like the original poster is encountering an issue with receiving a response as an object rather than an array.

To address this, custom code needs to be implemented along with necessary checks,

Additionally, it's essential to define mdata as type any due to its variability.

Within your subscribe function,

.subscribe((mdata : any) => {
    if(mdata['Temp']){
        let temp1 = mdata['Temp'].map(mdata => mdata.temp);
        let time = mdata['Temp'].map(mdata => mdata.time);
    } else {
        let temp1 = mdata.temp;
        let time = mdata.time;
    }
}

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 there a way to incorporate a map without altering the existing configuration settings?

I am considering integrating a map into my website using ANGULAR 2 and ESRI. Is there a way to do this without having to modify the configuration settings? ...

finding the parent of form controls in Angular 2 requires understanding the hierarchical structure

Is there a way to access the parent form group of a nested form group in order to retrieve a sibling control value during validation? Both controls are within a formGroup that is part of a formArray. While I am aware of the root element, I am unsure how ...

The AJAX request I'm making is not behaving as I anticipated when returning JSON data

I'm currently working on building an ajax call to compare my database and automatically update a div if any changes are detected. JavaScript is still quite new to me, especially when it comes to dealing with JSON data. I suspect the issue lies in ho ...

How can you retrieve a specific value from a JSON dictionary in Python using key chaining?

Suppose I have the Json data as shown below: { "a": { "b" : { "c" : "value" } } } This Json data is then loaded into my object (obj) using json.load() Now, I also have anoth ...

Chainr.transform is returning a transformedObject as Null

I have a task to convert a JSONObject using Jolt from one format to another. The original input I am working with is: { "a":"ABC", "b":"ABC1", "c":1, "d":2, "e":"ABC2&quo ...

Efficiently merging strings and arrays to create flawless JSON data

After fetching data from an XML document and storing them in three variables - the root element name, an array containing all the names of the root's children, and a second array with the length of those children sub-nodes, I am trying to convert thes ...

How can code snippets be showcased in an HTML page using Angular?

How can I display static code on a webpage using Angular? Is there a method to showcase code snippets in an HTML document? ...

Image Viewer Plugin for Ionic Framework

Looking for an Ionic plugin that allows displaying images with zoom functionality and rotate buttons. If not, any suggestions on how to add a rotate button using Ionic native photo viewer? ...

Troubleshooting a specialized Flask app example with JSON integration, encountering Attribute Error

Looking for a way to receive all errors as JSON in my webservice, I came across this code snippet: http://flask.pocoo.org/snippets/83/. However, when attempting to implement it, I encountered the following stack trace: 127.0.0.1 - - [30/Oct/2016 00:27:57] ...

Tips for managing errors in HTTP observables

I'm currently facing a challenge with handling HTTP errors in an Angular2 observable. Here's what I have so far: getContextAddress() : Observable<string[]> { return this.http.get(this.patientContextProviderURL) .map((re ...

Unable to trigger click or keyup event

After successfully implementing *ngFor to display my data, I encountered an issue where nothing happens when I try to trigger an event upon a change. Below is the snippet of my HTML code: <ion-content padding class="home"> {{ searchString ...

In TypeScript, what is the return Type of sequelize.define()?

After hearing great things about TypeScript and its benefits of static typing, I decided to give it a try. I wanted to test it out by creating a simple web API with sequelize, but I'm struggling to understand the types returned from sequelize. Here ar ...

Golang decodes JSON using static typing rather than dynamic typing

I used to believe that json.Marshal utilized reflection to examine the passed type and then decoded it accordingly. However, I encountered an issue when I had a variable with a static type of any which actually stored a struct, and when passed to json.Unma ...

What is the best way to loop through each child element and retrieve a specific element?

I am working on a find() function that searches for an element by tag name within a nested structure. I have attempted to iterate through all the children elements to locate the matching element. function find(tag: string) { let children = data.childr ...

Angular implementation of reverse geocoding

retrieveAddress(lat: number, lng: number) { console.log('Locating Address'); if (navigator.geolocation) { let geocoder = new google.maps.Geocoder(); let latlng = new google.maps.LatLng(lat, lng); let request = { LatLng: latlng }; ...

Analyzing a JSON object against a model or filter in Python

In my possession is a JSON file containing numerous objects structured like the example below: data { "cars": [ { "make": "honda", "model": "accord", "t ...

Is JSON a secure choice for handling sensitive information?

After stumbling upon an interesting article some time ago, I had a thought-provoking question for the CI community. How do you handle private data such as email addresses, permissions, and any user data that is considered sensitive? Dealing with public da ...

Utilizing Realm for Establishing Many-To-1 Relationship in Xamarin.Forms through Backlinking

Currently, I am in the process of developing an application using Xamarin.Forms with Realm as the local database, and I am encountering some challenges. The app is designed to consume an external API that provides a JSON response structured like this: [ ...

Utilizing External Libraries in Angular Full Stack Development

Currently, I am delving into the realm of Angular Full stack which incorporates Angular 2. As a newcomer to this technology, I have noticed that the setup and structure between pure Angular 2 and the Full stack can be quite distinct. This has led me to enc ...

Tips on accessing dictionaries with multiple values in JavaScript

I am struggling with a particular dictionary in my code: {1:['a&b','b-c','c-d'],2:['e orf ','f-k-p','g']} My goal is to print the key and values from this dictionary. However, the code I att ...