如何用 Go 解析 Json
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:}}
如何获取国籍的字段和值?
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)
Refer this link for complete code -> https://play.golang.org/p/vFgpE0GNJ7K
- 将结构更改为切片(
info
表示结构列表)
- 你
struct field
一定是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
}
有这个代码:
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:}}
如何获取国籍的字段和值?
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)
Refer this link for complete code -> https://play.golang.org/p/vFgpE0GNJ7K
- 将结构更改为切片(
info
表示结构列表) - 你
struct field
一定是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
}