How to parse a Json with Go

huangapple go评论92阅读模式
英文:

How to parse a Json with Go

问题

有这样的代码:

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:}}

我如何获取国籍(nationality)的字段和值?

英文:

Have tis code:

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)
}

When compile I get

{info:{field: Value:}}

How can I get the field and value of nationality?

答案1

得分: 1

  1. 将结构体改为切片(info代表结构体列表)
  2. 你的结构体字段必须是公开的(MarshalUnmarshalA Tour of GO

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

type Guyy struct {
  Info []Foo // 👈 公开的切片
}

PLAYGROUND

英文:
  1. Change struct to slice (info represent list of structs)
  2. You struct field must be exported (Marshal, Unmarshal, A Tour of GO)

> Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted...

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

<kbd>PLAYGROUND</kbd>

答案2

得分: -1

以下是要翻译的内容:

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

英文:
var Guy Guyy
var f interface{}
json.Unmarshal([]byte(GuyJson), &amp;f)

m := f.(map[string]interface{})

foomap := m[&quot;info&quot;]
v := foomap.([]interface{})

for _, fi := range v {
	vi := fi.(map[string]interface{})

	var f Foo
	f.Field = vi[&quot;field&quot;].(string)
	f.Value = vi[&quot;value&quot;].(string)

	if f.Field == &quot;nationality&quot; {
		fmt.Println(f.Field, &quot;was found to be&quot;, f.Value)
	}

	Guy.Info = append(Guy.Info, f)
}

fmt.Println(Guy)

> Refer this link for complete code -> https://play.golang.org/p/vFgpE0GNJ7K

huangapple
  • 本文由 发表于 2021年9月2日 14:18:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/69025038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定