【问题标题】:How to parse a Json with Go如何用 Go 解析 Json
【发布时间】:2021-09-02 06:18:19
【问题描述】:

有代码:

type Foo struct {
  field string
  Value string  

  }

type Guyy struct {
  info Foo
  
  }

func main() {
    GuyJson := `{"info":[{"field":"phone","value":"11111-11111"},{"field":"date","value":"05072001"},{"field":"nationality","value":"american"},{"field":"dni","value":"000012345"}]}`
    var Guy Guyy    
    json.Unmarshal([]byte(GuyJson), &Guy)
    fmt.Printf("%+v", Guy)
}

编译时我得到

{info:{field: Value:}}

如何获取国籍的字段和值?

【问题讨论】:

  • 您是否使用例如连接到 Postgres pq,或者只是解析 psql 输出?如果是后者,为什么?
  • "是否有可能得到 natiolanity 值?" -- 是的,有可能。如果您尝试过但失败,请显示代码,显示您的努力。如果你还没有尝试过,为什么不呢?请注意,它看起来不像“psql 数组”,而是看起来像 PostgreSQL jsonb 类型的值,并且解析 json 通常在 Go 中非常简单,您会发现成千上万的帖子关于这个就在stackoverflow上。我建议您在询问之前先进行一些研究并编写一些代码。
  • 抱歉,我更新了问题
  • 我已经从行中分配了数据,假装已经执行了查询
  • 一旦你把它弄下来,你可以遍历Info字段,它现在是一个切片,检查每个元素的Field值是否是"nationality",当你得到一个匹配然后你可以取元素的Value 值。

标签: sql arrays go psql


【解决方案1】:
  1. 将结构更改为切片(info 表示结构列表)
  2. struct field必须是exportedMarshalUnmarshalA Tour of GO

结构值编码为 JSON 对象。每个导出的 struct 字段都成为对象的成员,使用字段名称作为对象键,除非该字段被省略...

type Guyy struct {
  Info []Foo // ? exported slice 
}

PLAYGROUND

【讨论】:

    【解决方案2】:
    var Guy Guyy
    var f interface{}
    json.Unmarshal([]byte(GuyJson), &f)
    
    m := f.(map[string]interface{})
    
    foomap := m["info"]
    v := foomap.([]interface{})
    
    for _, fi := range v {
        vi := fi.(map[string]interface{})
    
        var f Foo
        f.Field = vi["field"].(string)
        f.Value = vi["value"].(string)
    
        if f.Field == "nationality" {
            fmt.Println(f.Field, "was found to be", f.Value)
        }
    
        Guy.Info = append(Guy.Info, f)
    }
    
    fmt.Println(Guy)
    

    完整代码参考此链接 -> https://play.golang.org/p/vFgpE0GNJ7K

    【讨论】:

      猜你喜欢
      • 2016-12-16
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多