访问JSON数组中的项目并显示对象数据

时间:2018-05-09 23:59:40

标签: json api

我正在尝试使用天气API并获取JSON数组中第一个对象的开放数据。相反,我得到了所有对象。我如何访问JSON数组中的第一个对象?还有如何使数据显示而不是[对象,对象]。 现在它看起来像这样:

enter image description here

看起来应该更像这样:

      "name":"msl",
      "levelType":"hmsl",
      "level":0,
      "values":[
        1031

这是我的代码:    HTML:

     <ion-header>
       <ion-navbar>
         <ion-title>New App</ion-title>
        </ion-navbar>
        </ion-header>

      <ion-content padding class="no-scroll">
      <ion-grid>
      </ion-row>
       <button ion-button (click) = "getData()">Get Data</button>
        <ion-row>{{result.timeSeries}}</ion-row>

   <ion-row>
        <ion-col>
         </ion-grid>
         </ion-content>

TS代码:

import { Component, state } from '@angular/core';
import { NavController, AlertController, Platform, Alert} from 'ionic-angular';
import { MapPage } from '../map/map';
import { NewGamePage } from '../new-game/new-game';
import {AchievmentPage} from '../achievment/achievment';
import {DailyRoutesPage}from '../daily-routes/daily-routes';

import { LocalNotifications } from '@ionic-native/local-notifications'
import { PhonegapLocalNotification } from "@ionic-native/phonegap-local-notification";
import { Push, PushObject, PushOptions} from '@ionic-native/push'

import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";


 @Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

      result: any = [];
      data: Observable<any>;


  constructor(public navCtrl: NavController, public alertCtrl: AlertController, private platform: Platform, private localNotification: LocalNotifications, private notiPhoneGap: PhonegapLocalNotification, public http: HttpClient) {
  }
   getData(){
    var url = `https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/16.158/lat/58.5812/data.json`;  
    this.data = this.http.get(url);
    this.data.subscribe(data=>{
      this.result = data;
    })
  }



}

1 个答案:

答案 0 :(得分:0)

您可以使用内置的JSON.stringify功能“字符串化”数据。您需要在第三个参数中指定填充。

忽略CORS代理,我只是用它来绕过同源策略。

var apiUrl = 'https://opendata-download-metfcst.smhi.se/api';
var apiPointUrl = `${apiUrl}/category/pmp3g/version/2/geotype/point`;

// Builds an API url to get a point at a set of coordinates.
function getPointData(longitude, latitude) {
  return `${apiPointUrl}/lon/${longitude}/lat/${latitude}/data.json`;
}

// Wrapping with a CORS proxy so that there is no issue with Same-Origin-Policy
var requestQuery = `https://cors.io/?${getPointData(16.158, 58.5812)}`;

$.getJSON(requestQuery, (result, status, xhr) => {
  // Display the first two hours in the timeSeries.
  console.log(JSON.stringify(result.timeSeries.slice(0, 2), null, 2));
});
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>