英文:
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"}
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论