2016-04-19 5 views
0

Ich bekomme die folgende Antwort in einer URL und möchte sie entpacken, aber ich kann dies nicht tun. Dies ist die Art von Antwort, die ich gerne entpacken würde.JSON-Array in Golang kann nicht entpackt werden

[ 
    {"title": "Angels And Demons", "author":"Dan Brown", "tags":[{"tagtitle":"Demigod", "tagURl": "/angelDemon}] } 
    {"title": "The Kite Runner", "author":"Khalid Hosseinei", "tags":[{"tagtitle":"Kite", "tagURl": "/kiteRunner"}] } 
    {"title": "Dance of the dragons", "author":"RR Martin", "tags":[{"tagtitle":"IronThrone", "tagURl": "/got"}] } 
] 

Ich versuche, diese Art von Antwort zu entlarven, aber nicht in der Lage, dies zu tun. Dies ist der Code, den ich versuche zu schreiben.

res, err := http.Get(url) 
if err != nil { 
    log.WithFields(log.Fields{ 
     "error": err, 
    }).Fatal("Couldn't get the html response") 
} 
defer res.Body.Close() 
b, err := ioutil.ReadAll(res.Body) 
if err != nil { 
    log.WithFields(log.Fields{ 
     "error": err, 
    }).Fatal("Couldn't read the response") 
} 

s := string(b) 

var data struct { 
    Content []struct { 
     Title   string `json:"title"` 
     Author   string `json:"author"` 
     Tags   map[string]string `json:"tags"` 
    } 
} 

if err := json.Unmarshal([]byte(s), &data); err != nil { 
    log.WithFields(log.Fields{ 
     "error": err, 
    }).Error("Un-marshalling could not be done.") 
} 

fmt.Println(data.Content) 

Kann mir bitte jemand in dieser Hinsicht helfen? Vielen Dank im Voraus.

+0

Was ist die Fehlermeldung, die Sie erhalten? –

+0

error = "json: Array kann in Go-Wert vom Typ struct {Content [] struct nicht entpackt werden –

Antwort

0

ändert es

var data struct { 
    Content []struct { 
     Title   string `json:"title"` 
     Author   string `json:"author"` 
     Tags   map[string]string `json:"tags"` 
    } } 

dazu

type Content struct { 
     Title   string `json:"title"` 
     Author   string `json:"author"` 
     Tags   map[string]string `json:"tags"` 

} 
var data []Content 
0

Betrachten Sie es in ein Stück Inhalt unmarshalling:

type Content struct { 
    Title string   `json:"title"` 
    Author string   `json:"author"` 
    Tags map[string]string `json:"tags"` 
} 

// Send in your json 
func convertToContent(msg string) ([]Content, error) { 
    content := make([]Content, 0, 10) 

    buf := bytes.NewBufferString(msg) 
    decoder := json.NewDecoder(buf) 

    err := decoder.Decode(&content) 
    return content, err 
} 

prüft ein Beispiel mit Ihrem Anwendungsfall hier ansehen: http://play.golang.org/p/TNjb85XjpP

0

Ich konnte dieses Problem lösen, indem ich eine einfache Änderung im obigen Code durchführte.

var Content []struct { 
    Title   string `json:"title"` 
    Author   string `json:"author"` 
    Tags   map[string]string `json:"tags"` 
} 

Vielen Dank für Ihre Antworten.

Verwandte Themen