Can i format dynamically created json into the required format for dev express charts

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

Can i format dynamically created json into the required format for dev express charts

问题

我已经为http请求编写了一个go程序,以json格式作为响应,但是我只能创建以下格式的json:

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

内容类型是使用map[string]string动态定义的。有人可以帮我以以下格式提供json吗?

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

请帮帮我。

英文:

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

得分: 3

你只需要创建一个结构体切片即可。以下是根据文档示例进行的修改:

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)

这将产生以下输出:

[
    {"Country":"abc","Population":"1234"},
    {"Country":"def","Population":"567"}
]
英文:

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"}
]

huangapple
  • 本文由 发表于 2015年1月6日 21:06:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/27799326.html
匿名

发表评论

匿名网友

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

确定