dpdrtj1075 2018-10-25 14:53
浏览 932

如何从golang中的json中获取特定值

Not quite sure how to access the value I'm interested in. What I have is response from my couchDB that looks like this:

response from couchDB in json format

What I am interested in is to get out the "name" and "phone" value using golang.

If I run this code, I at least get out the value of id or key:

package main

import(
    "net/http"
    "encoding/json"
    "io/ioutil"
    "fmt"
)

type rows struct{
    Rows []info `json:"rows"`
}

type info struct{
    Name string `json:"id"`
}


func main() {
    resp, err := http.Get("http://localhost:5984/mydb/_all_docs?include_docs=true")
    bytes, _ := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    var d rows
    json.Unmarshal(bytes, &d)
    fmt.Println(d)
}

Output from script

So I tried doing it this way to get "name" for starter:

package main

import(
    "net/http"
    "encoding/json"
    "io/ioutil"
    "fmt"
)

type rows struct{
    Rows []doc `json:"rows"`
}

type doc struct {
  Values []info `json:"doc"`
}

type info struct{
    Name string `json:"name"`
}


func main() {
    resp, err := http.Get("http://localhost:5984/mydb/_all_docs?include_docs=true")
    bytes, _ := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    var d rows
    json.Unmarshal(bytes, &d)
    fmt.Println(d)
}

But get this response: Output from script

I'm pretty new to golang but really want to learn how to build simple API with it, if there are any other ways to do this in golang please let me know

  • 写回答

1条回答 默认 最新

  • dongzhao3040 2018-10-25 15:31
    关注

    Here's how I would approach this problem

    1) get the example json output and visit the website https://mholt.github.io/json-to-go/

    Use this to automatically generate a struct that matches your data You may need to adjust what it makes to give you a "row" struct

    2) Using the structs you have just devised, load the data with Unmarshall

    3) dump the data with the %v Printf format to look at it and then work out how to get at the name and phone elements

    You would have some example code here but your example data is in a picture so is time consuming to reproduce: sorry :/

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮