Skip to content

Instantly share code, notes, and snippets.

@saml
Created February 8, 2016 22:41
Show Gist options
  • Save saml/23ddc52ee3562a5a2a93 to your computer and use it in GitHub Desktop.
Save saml/23ddc52ee3562a5a2a93 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type WebPage struct {
Body []map[string]Values `json:"body"`
}
// Only one of them are set.
type Values struct {
Entrytext *string `json:"entrytext"`
EntryText *string `json:"entryText"`
Url *string `json:"url"`
Html *string `json:"html"`
}
func (v *Values) HTML() string {
if v.Entrytext != nil {
return *v.Entrytext
}
if v.EntryText != nil {
return *v.EntryText
}
if v.Url != nil {
return fmt.Sprintf(`<img src="%s">`, *v.Url)
}
if v.Html != nil {
return *v.Html
}
return ""
}
func (p *WebPage) HTML() string {
var buffer bytes.Buffer
for _, m := range p.Body {
for k := range m {
v := m[k]
s := v.HTML()
if s != "" {
buffer.WriteString(s)
}
break
}
}
return buffer.String()
}
const input = `{
"body": [{
"entrytitle": {}
}, {
"entry": {
"entrytext": "<p>hello</p>"
}
}, {
"image": {
"url": "http://google.com/a.jpg",
"width": 100
}
}, {
"entry_0": {
"entryText": "<p>world</p>"
}
}, {
"htmlcomponent[23]": {
"html": "<p>hello</p>"
}
}]
}`
func main() {
var p WebPage
if err := json.Unmarshal([]byte(input), &p); err != nil {
log.Fatal(err)
}
log.Print(p.HTML())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment