如何在Go中访问JSON响应?

57hvy0tb  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(106)

我在发JSON请求

req, err := http.NewRequest("GET", myPath, nil)
if err != nil {
  panic(err)
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
  panic(err)
}

defer resp.Body.Close()
var j map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&j)
if err != nil {
  panic(err)
}

现在返回一个map[string]interface{}
但JSON中数据的实际形状是:

{
  key1: "string"
  key2: "string"
  key3: [
   { key1: "string", key2: "int", key3: "Array<string>" },
   { key1: "string", key2: "int", key3: "Array<string>" },
   ...a lot more
  ] 
}

我如何才能真正获得key3数据?

for key, value := range j {
  if key == "key3" {
    // Im stuck here, 
  }
}

我尝试将JSON响应解组为结构体,并将其解码为该结构体

type key3Struct struct {
  key1 string
  key2 string
  key3 []string
}

type ResponseStruct struct {
  key1 string
  key2 string 
  key3 []key3Struct
}

// Attempt 1
j = ResponseStruct{}
json.NewDecoder(resp.Body).Decode(&j)
==> error cant convert map[string]interface{} to ResponseStruct{}

// Attempt 2
json.Unmarshal(resp.Body, &j)
==> it looks like [ {} ] no data in it...
amrnrhlw

amrnrhlw1#

感谢@mkopriva的帮助,我的问题是两件事:1 -我没有为struct props提供大写字母2 -我没有将它们声明为json
解决方案:

type key3Struct struct {
  Key1 string `json:"key1"`
  Key2 string `json:"key2"`
  Key3 []string `json:"key3"`
}

type ResponseStruct struct {
  Key1 string `json:"key1"`
  Key2 string  `json:"key2"`
  Key3 []key3Struct `json:"key3"`
}

相关问题