获取特定键的值

我是一个从数据库中获取这样的字符串。

[{“Key”:“a”,“Value”:“4521”},{“Key”:“b”,“Value”:“7”}]

我想得到键“b”的值。在 Go 中执行此操作的最佳方法是什么?


慕田峪4524236
浏览 77回答 1
1回答

米琪卡哇伊

package mainimport (    "encoding/json"    "fmt"    "log")func main() {    str := `[{"Key":"a","Value":"4521"},{"Key":"b","Value":"7"}]`    // declaring out struct we will use for unmarshaling and iteration check.    out := []struct {        Key, Value string    }{}    if err := json.Unmarshal([]byte(str), &out); err != nil {        log.Fatal(err)    } else {        // searching for value.        for i := range out {            if out[i].Key == "b" {                fmt.Println("Found", out[i].Value)                return            }        }    }}这是一种简单的方法,而不是最佳的。最佳伤口是手动解析字符串,逐个字节。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go