douli0531
douli0531
2015-01-06 13:06

我可以将动态创建的json格式化为开发快递图表所需的格式吗

已采纳

I have written a go program for giving json as a response to the httpRequest,but i am able to create json in this format only :

{
  "Country": [
        "abc",
        "def",

    ],
    "Population": [
        "8388344",
        "343",

    ]
}

The content types are dynamically defined using map[string]string.Can someone please help me out to give the json in the below format:

[
    {
       "Country" :"abc",
       "Population" :"8388344"
    },
    {
        "Country" : "def",
        "Population" :"343"
    },
    ...
]

Please help me out..

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douci1615 douci1615 6年前

    You just need to make a slice of structs. Adapted from the doc example:

    type Tuple struct {
        Country    string
        Population string
    }
    tuples := []Tuple{
        {Country: "abc", Population: "1234"},
        {Country: "def", Population: "567"},
    }
    
    b, err := json.Marshal(tuples)
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)
    

    This produces:

    [
        {"Country":"abc","Population":"1234"},
        {"Country":"def","Population":"567"}
    ]
    
    点赞 评论 复制链接分享