2017-07-04 5 views
2

Je suis nouveau sur Go. Je travaille avec une API météo, j'ai commenté les sections qui causent l'erreur J'ai vu plusieurs autres liens qui ont un problème similaire, mais aucun d'entre eux ne semble avoir le tableau au milieu de la chaîne JSON.Je suis sûr qu'il y a un moyen de définir la structure avec une tranche.Je n'arrive pas à obtenir la syntaxe permettre Voici où je suis coincé..unmarshal json array dans go struct (array est au milieu de la chaîne JSON

package main 

import (
    "encoding/json" 
    "fmt" 
    "io/ioutil" 
    "log" 
    "net/http" 
) 

// WeatherData struct to collect data from the API call 
type WeatherData struct { 
    Wind Wind 
    Sys Sys 
    // Weather Weather 
    Name string `json:"name"` 
} 

////////////// ERROR when unmarshalling this struct ///////// 
// Weather provides basic weather info 
// type Weather struct { 
// ID  int `json:"id"` 
// Descrip string `json:"description"` 
// Icon string `json:"icon"` 
// } 
///////////////////////////////////////////////////////////// 

// Sys includes sunrise, sunset, country, etc. 
type Sys struct { 
    Country string `json:"country"` 
} 

// Wind struct to get specific wind characteristics 
type Wind struct { 
    Speed float64 `json:"speed"` 
    Degree float64 `json:"deg"` 
    Gust float64 `json:"gust"` 
} 

func main() { 
    res, getErr := http.Get("http://api.openweathermap.org/data/2.5/weather?zip=REMOVED,us&appid=REMOVEDBUTWILLPOSTJSONData") 
    if getErr != nil { 
     log.Fatalln("http.Get error: ", getErr) 
    } 
    defer res.Body.Close() 
    body, readErr := ioutil.ReadAll(res.Body) 
    if readErr != nil { 
     log.Fatalln("Read Error: ", readErr) 
    } 
//////////// UNABLE TO UNMARSHAL the array that passes through here //// 
    var data WeatherData 
    if err := json.Unmarshal(body, &data); err != nil { 
     panic(err) 
    } 

    fmt.Println("Wind gusts: ", data.Wind.Gust) 
    fmt.Println("Wind speed: ", data.Wind.Speed) 
    fmt.Println("Wind degrees: ", data.Wind.Degree) 

    fmt.Println("Country is: ", data.Sys.Country) 
    fmt.Println("City is: ", data.Name) 

///////////////// CAN'T ACCESS Description...or anything in Weather 
// fmt.Println("Country is: ", data.Weather.Descrip) // cannot access due to this portion being inside an array 

} 



/////////////////THIS IS THE JSON DATA THAT IS AVAILABLE /////////// 
{ 
    "coord": { 
    "lon": -97.31, 
    "lat": 32.94 
    }, 
    "weather": [ // CAN'T ACCESS THIS CORRECTLY 
    { 
     "id": 800, 
     "main": "Clear", 
     "description": "clear sky", 
     "icon": "01d" 
    } 
    ], 
    "base": "stations", 
    "main": { 
    "temp": 306.46, 
    "pressure": 1014, 
    "humidity": 55, 
    "temp_min": 306.15, 
    "temp_max": 307.15 
    }, 
    "visibility": 16093, 
    "wind": { 
    "speed": 5.1, 
    "deg": 150, 
    "gust": 7.2 
    }, 
    "clouds": { 
    "all": 1 
    }, 
    "dt": 1499120100, 
    "sys": { 
    "type": 1, 
    "id": 2597, 
    "message": 0.0225, 
    "country": "US", 
    "sunrise": 1499081152, 
    "sunset": 1499132486 
    }, 
    "id": 0, 
    "name": "Fort Worth", 
    "cod": 200 
} 
+0

Liens supplémentaires J'ai regardé avec un problème similaire, mais les solutions ne correspondent pas tout à fait mon scénario: https://stackoverflow.com/questions/ 40626125/golang-unmarshal-json-ne peut pas-unmarshal-tableau-dans-aller-valeur-de-type-principal-moni –

+0

Ce lien semble le plus proche, mais je ne sais pas comment créer un unmarshaller personnalisé selon leur solution description ... https://stackoverflow.com/questions/42377989/unmarshal-json-array-of-arrays-in-go –

+0

MISE À JOUR: Ca ne marche toujours pas, mais j'ai changé: 'type WeatherData struct { \t Vent Vent \t Sys Sys \t Météo [] Météo ////////// les valeurs s'affichent, mais il semble que je ne puisse pas identifier les valeurs en fonction de leurs clés \t 'json:" name "' } ' –

Répondre

3

Vous devez définir une tranche de Weather struct dans WeatherData

Uncomment Weather structure et mise à jour WeatherData structure à suivre.

// WeatherData struct to collect data from the API call 
type WeatherData struct { 
    Wind Wind  `json:"wind"` 
    Sys  Sys  `json:"sys"` 
    Weather []Weather `json:"weather"` 
    Name string `json:"name"` 
} 

S'il vous plaît jeter un oeil sur le code exemple: https://play.golang.org/p/4KFqRuxcx2

+0

Merci d'essayer d'aider, mais j'ai été capable de le faire et d'obtenir le morceau de données de tableau, mais je ne peux toujours pas appeler une clé/valeur individuelle pour quelque chose comme des données .Weather.Descrip retourne l'erreur qu'elle est indéfinie. J'ai également essayé d'ajouter le type [] map [string] interface {} qui fonctionne pour me donner toutes les paires clé/valeur, mais je ne peux toujours pas les appeler. Vous pouvez voir ma modification ici: [link] (https://play.golang.org/p/MaZ5wMuJVA) –

+0

Vous devez accéder aux valeurs de tranches/tableaux via l'index, voir ici: [link] (https: // play. golang.org/p/zks-JPQ1YY). – jeevatkm

+0

Ça marche! Merci beaucoup. Je suis même allé jusqu'à accéder à l'ensemble de l'index 0, mais je ne me suis pas rendu compte que je pouvais faire de la notation par points en plus. Merci encore! –