Golang JSON数组

时间:2018-02-19 20:32:11

标签: go passwords

我正在尝试使用WordNik()为此脚本获取字典的随机单词:https://github.com/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来请求副词,名词等,然后根据这些词创建一个字典来生成密码。我对阵列和处理数据很恐怖。

1 个答案:

答案 0 :(得分:0)

正如评论中指出的那样,您需要导出字段以便可以解组

encoding / json包依赖于反射,因为它在另一个包中,所以它无法访问未导出的字段。 (以小写字母开头的字段,字段,方法或函数未导出,而大写字母则导出)

然后你的示例json根本不包含WordList,所以你想要的是直接解组到Words数组中。单词对象也只包含Id和Word,而不是数组本身。

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<查看此工作示例以供参考。