英文:
How to add a valid json string to an object
问题
我目前有这样的代码:
type Info struct {
Ids []string `json:"ids"`
assignment string `json:"assignment"`
}
现在我的assignment
是一个大的硬编码的 JSON 字符串,从文件中读取。我正在做这样的事情:
r := Info{Ids: names, assignment: existingJsonString}
body, _ := json.Marshal(r)
然而,上面的body
是不正确的,因为assignment
出现为字符串而不是 JSON 对象。我该如何告诉Info
结构体,assignment
将是一个 JSON 字符串而不是普通字符串,以便json.Marshal
可以正确处理它?
英文:
I currently have something like this
type Info struct {
Ids []string `json:"ids"`
assignment string `json:"assignment"`
}
Now my assignment
is a large hardcoded json string that is read from a file.
I am doing something like this
r := Info{Ids: names, assignment: existingJsonString}
body, _ := json.Marshal(r)
However the above body
is incorrect as assignment appears as string and not a json object. How can I tell the info struct that assignment
will be a json string and not a regular string so that json.Marshal
plays well with it ?
答案1
得分: 3
使用类型 json.RawMessage,请注意 assignment
应该是可导出的:
type Info struct {
Ids []string `json:"ids"`
Assignment json.RawMessage `json:"assignment"`
}
示例:
package main
import (
"encoding/json"
"fmt"
)
type Info struct {
Ids []string `json:"ids"`
Assignment json.RawMessage `json:"assignment"`
}
func main() {
r := Info{
Ids: []string{"id1", "id2"},
Assignment: json.RawMessage(`{"a":1,"b":"str"}`),
}
body, err := json.Marshal(r)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", body)
}
英文:
Use the type json.RawMessage, and please note that assignment
should be exported:
type Info struct {
Ids []string `json:"ids"`
Assignment json.RawMessage `json:"assignment"`
}
Example:
package main
import (
"encoding/json"
"fmt"
)
type Info struct {
Ids []string `json:"ids"`
Assignment json.RawMessage `json:"assignment"`
}
func main() {
r := Info{
Ids: []string{"id1", "id2"},
Assignment: json.RawMessage(`{"a":1,"b":"str"}`),
}
body, err := json.Marshal(r)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", body)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论