2013-06-12 14 views
8

Quindi ho il seguente bit di JSON e voglio estrarre il valore "$ t" sotto "token". Proseguire per il codice Go ...golang: accesso rapido ai dati delle mappe all'interno delle mappe

{ 
    "@encoding": "iso-8859-1", 
    "@version": "1.0", 
    "service": { 
    "auth": { 
     "expiresString": { 
     "$t": "2013-06-12T01:15:28Z" 
     }, 
     "token": { 
     "$t": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 
     }, 
     "expires": { 
     "$t": "1370999728" 
     }, 
     "key": { 
     "$t": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 
     } 
    } 
} 

Ho il seguente frammento di codice Go che unmarshal il JSON in un'interfaccia. Quindi lavoro fino al valore "$ t" di "token". Questo approccio funziona, ma è brutto.

La mia domanda: c'è un modo più veloce per accedere a quel valore rispetto alla conversione di ogni mappa in un'interfaccia? Sono molto nuovo per andare e non sono a conoscenza di molte delle utili funzionalità di interfacce e mappe.

var f interface{} 
jerr := json.Unmarshal(body, &f) 
m := f.(map[string]interface{}) 
ser := m["service"].(map[string]interface{}) 
a := ser["auth"].(map[string]interface{}) 
tok := a["token"].(map[string]interface{}) 
token := tok["$t"] 
fmt.Fprintf(w, "Token: %v\n", token) 

Grazie in anticipo!

risposta

11

Se questo è l'unico valore che si desidera, come utilizzare un anonimo struct che definisce il percorso dei dati.

var m = new(struct{Service struct{Auth struct{Token map[string]string}}}) 

var err = json.Unmarshal([]byte(data), &m) 

fmt.Println(m.Service.Auth.Token["$t"], err) 

DEMO:http://play.golang.org/p/ZdKTzM5i57


Invece di utilizzare un map per i dati più intimi, si potrebbe utilizzare un altro struct, ma avremmo bisogno di fornire un tag campo per l'alias nome.

var m = new(struct{Service struct{Auth struct{Token struct{T string `json:"$t"`}}}}) 

var err = json.Unmarshal([]byte(data), &m) 

fmt.Println(m.Service.Auth.Token.T, err) 

DEMO:http://play.golang.org/p/NQTpaUvanx

+0

Molto bello . Grazie per aver incluso entrambe le versioni. – turnerd18

+0

Prego. –

Problemi correlati