Golang JSON Array



我正在尝试使用wordnik((获取此脚本字典的随机单词:https://github.com/jmagrippis/jmagrippis/password

Wordnik正在输出:

[{"id":7936915,"word":"Tanganyikan"},{"id":27180,"word":"cartographic"},{"id":48094,"word":"deterministic"},{"id":1485119,"word":"higher-risk"},{"id":120986,"word":"juristic"},{"id":1830806,"word":"magnetorheological"},{"id":320495,"word":"quelled"},{"id":324610,"word":"remoter"},{"id":215158,"word":"telemetric"},{"id":225207,"word":"uninquisitive"}]

这是我的代码:

package main
import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "time"
    "github.com/jmagrippis/password"
)
type Words struct {
    id   []int64
    word []string
}
type GetWordsResponse struct {
    WordList []Words
}
func getWords(speech string) (*GetWordsResponse, error) {
    url := fmt.Sprintf("http://api.wordnik.com/v4/words.json/randomWords?hasDictionaryDef=false&includePartOfSpeech=%s&minCorpusCount=0&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=5&maxLength=-1&limit=10&api_key=api_key", speech)
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var s = new(GetWordsResponse)
    var arr []string
    _ = json.Unmarshal([]byte(body), &arr)
    log.Printf("Unmarshaled: %v", arr)
    return s, err
}
func main() {
    dictionary := &password.Dictionary{
        Adjectives: []string{"beautiful", "homely", "magical", "posh", "excellent"},
        Subjects:   []string{"mermaids", "unicorns", "lions", "piranhas"},
        Verbs:      []string{"love", "fancy", "eat", "bring", "fear", "aggravate"},
        Adverbs:    []string{"cuddling", "slapping", "shouting", "jumping"},
        Objects:    []string{"teddy-bears", "diamonds", "buckets", "boxes"},
    }
    generator := password.NewGenerator(dictionary, time.Now().UnixNano())
    pass := generator.Generate()
    fmt.Printf("%s", pass)
    getWords("Verb")
}

您可以看到,我要做的就是使用Wordnik API请求副词,名词等,然后根据这些单词制作字典来生成密码。我对数组和处理数据感到恐惧。

如您需要导出的注释中指出的那样

编码/JSON软件包依赖于反射,并且由于它在另一个软件包中,因此它无法访问未备份的字段。(在Go中,以小字母开头的字段,方法或功能是未陈述的(,而用大写字母出口(

然后,您的示例JSON根本不包含WordList,因此您想要的是直接将单词列出。另外,一个单词对象仅由ID和单词组成,而不由数组本身组成。

type Words struct {
    Id   int64
    Word string
}
func main() {
    .... 
    var words []Words
    // you don't need to read the whole body first, you can decode in the same turn like this
    err := json.NewDecoder(req.Body).Decode(&words)
    if nil != err {
       log.Fatal(err)
    }
   ...
}

另一个非常重要的事情是您不应忽略错误。这将帮助您调试问题。(我的意思是_ = json.unmarshal(

至于从GO开始,您可以实现一个简单的测试,以查看您的代码是否按预期工作。

https://play.golang.org/p/nuz9uxdka5s<检查此工作示例以获取参考。

最新更新