英文:
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
- 将结构体改为切片(
info
代表结构体列表) - 你的结构体字段必须是公开的(Marshal,Unmarshal,A Tour of GO)
结构体值被编码为JSON对象。每个公开的结构体字段都成为对象的成员,使用字段名作为对象键,除非该字段被省略...
type Guyy struct {
Info []Foo // 👈 公开的切片
}
英文:
- Change struct to slice (
info
represent list of structs) - You
struct field
must beexported
(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), &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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论