douxiangui5011 2016-10-10 16:00
浏览 246
已采纳

如何使用golang在JSON中填充并添加嵌套数组?

I am trying to learn how to create and manipulate JSON in this format on the fly using golang:

{ 
"justanarray": [ 
    "One", 
    "Two" 
], 
"nestedstring": {"name": {"first": "Dave"}}, 
"nestedarray": [ 
    {"address": {"street": "Central"}},  
    {"phone": {"cell": "(012)-345-6789"}}  
] 
} 

I can create and manipulate everything but the nested array.

Here is a play for the code below. https://play.golang.org/p/pxKX4IOE8v

package main 

import ( 
        "fmt" 
        "encoding/json" 
) 





//############ Define Structs ################ 

//Top level of json doc 
type JSONDoc struct { 
        JustArray   []string    `json:"justanarray"` 
    NestedString    NestedString    `json:"nestedstring"` 
        NestedArray []NestedArray   `json:"nestedarray"` 


} 

//nested string 
type NestedString struct { 
        Name   Name   `json:"name"` 
} 
type Name struct { 
        First string `json:"first"` 
} 

//Nested array 
type NestedArray []struct { 
        Address   Address   `json:"address,omitempty"` 
        Phone Phone `json:"phone,omitempty"` 
} 
type Address struct { 
        Street string `json:"street"` 
} 
type Phone struct { 
        Cell string `json:"cell"` 
} 






func main() { 

        res2B := &JSONDoc{} 
    fmt.Println("I can create a skeleton json doc") 
    MarshalIt(res2B) 

    fmt.Println("
I can set value of top level key that is an array.") 
        res2B.JustArray = []string{"One"} 
    MarshalIt(res2B)    

    fmt.Println("
I can append this top level array.") 
        res2B.JustArray = append(res2B.JustArray, "Two") 
    MarshalIt(res2B) 

    fmt.Println("
I can set value of a nested key.") 
        res2B.NestedString.Name.First = "Dave" 
        MarshalIt(res2B) 


    fmt.Println("
How in the heck do I populate, and append a nested array?") 


} 

func MarshalIt(res2B *JSONDoc){ 
        res, _ := json.Marshal(res2B) 
        fmt.Println(string(res)) 
}

Thanks for any help.

  • 写回答

1条回答 默认 最新

  • drxm5014 2016-10-10 16:07
    关注

    Instead of defining NestedArray as a slice of anonymous structs, it's better to redefine it in JSONDoc as such:

    type JSONDoc struct {
        JustArray    []string          `json:"justanarray"`
        NestedString NestedString      `json:"nestedstring"`
        NestedArray  []NestedArrayElem `json:"nestedarray"`
    }
    
    //Nested array
    type NestedArrayElem struct {
        Address Address `json:"address,omitempty"`
        Phone   Phone   `json:"phone,omitempty"`
    }
    

    Then, you can do:

    res2B := &JSONDoc{}
    res2B.NestedArray = []NestedArrayElem{
        {Address: Address{Street: "foo"}},
        {Phone: Phone{Cell: "bar"}},
    }
    MarshalIt(res2B)
    

    Playground: https://play.golang.org/p/_euwT-TEWp.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题
  • ¥15 使用dify通过OpenAI 的API keys添加OpenAI模型时报了“Connection Error”错误