I want to get a string that represents a json like this one:
{ "votes": { "option_A": "3" } }
and include a "count" key in it所以结局是这样的:
{ "votes": { "option_A": "3" }, "count": "1" }
这就是为什么我计划将其转换为json,以便添加计数,然后
I want to get a string that represents a json like this one:
{ "votes": { "option_A": "3" } }
and include a "count" key in it所以结局是这样的:
{ "votes": { "option_A": "3" }, "count": "1" }
这就是为什么我计划将其转换为json,以便添加计数,然后
实际上,您只需要一个 struct ,正如注释中提到的,字段上的正确注释将产生所需的结果.JSON并不是一种非常不同的数据格式,它定义得很好,任何一段JSON,无论对你来说有多么复杂和混乱,都可以通过模式和Go及大多数其他OO编程语言中的对象来相当容易地、100%准确地表示.这里有一个例子;
package main
import (
"fmt"
"encoding/json"
)
type Data struct {
Votes *Votes `json:"votes"`
Count string `json:"count,omitempty"`
}
type Votes struct {
OptionA string `json:"option_A"`
}
func main() {
s := `{ "votes": { "option_A": "3" } }`
data := &Data{
Votes: &Votes{},
}
err := json.Unmarshal([]byte(s), data)
fmt.Println(err)
fmt.Println(data.Votes)
s2, _ := json.Marshal(data)
fmt.Println(string(s2))
data.Count = "2"
s3, _ := json.Marshal(data)
fmt.Println(string(s3))
}
https://play.golang.org/p/ScuxESTW5i
根据您最近的 comments ,您可以通过使用interface{}
来表示除计数之外的数据,将计数设为字符串,并将blob的其余部分插入到interface{}
中,该interface{}
基本上可以接受任何内容.话虽如此,Go是一种静态类型的语言,具有相当严格的类型系统.再说一遍,你说"它可以是任何东西"的 comments 是不正确的.JSON不可能是任何东西.对于任何一段JSON,都有一个模式,一个模式可以定义JSON的许多变体.我建议你花点时间来理解数据的 struct ,而不是把一些东西拼凑在一起,因为它们无法定义,而这对那些知道自己在做什么的人来说可能非常容易.