英文:
Store JSON Object "as is" into datastore
问题
我必须将一个嵌套的结构存储到数据存储中。由于在数据存储中展开嵌套结构会导致切片的切片问题,我想将JSON对象原样(作为字符串?)存储到数据存储中。在Go语言中是否可行?
英文:
I have to store a nested struct into datastore. As I'm running into the
datastore: flattening nested structs leads to a slice of slices: field
problem, I'd like to store the JSON object as is (as string?) to the datastore. Is this doable in Go?
答案1
得分: 3
是的,这在Go语言中是可行的。
无论您的数据存储结构有多复杂(或嵌套),都可以转换为JSON格式。只需确保map的键是字符串类型。
还要确保数据存储的元素是公开的(以大写字母开头)。如果您不想编码某个字段,可以将其保持为私有的(以小写字母开头)。
json.Marshal()函数将返回一个字节数组,可以将其保存到文件中。
type Complex struct {
Data1 map[string]int
Data2 []byte
TimeStamp time.Time
}
type Datastore struct {
Name string
Phones []string
Address map[string]string
noJson string // 不会被编码,因为它不是公开的
SomethingComplex map[string]Complex
}
英文:
Yes its doable in golang
However complex (or nested) your datastore is, it can be converted to json. Just make sure map's key is a string.
Also make sure elements of the datastore are public (starting with capital letter). If you don't want to encode a field you can keep it as private (beginning with small letter).
json.Marshal() will return a byte array, which can be saved into a file.
type Complex struct {
Data1 map[string]int
Data2 []byte
TimeStamp time.Time
}
type Datastore struct {
Name string
phones []string
Address map[string]string
noJson string // Wont be encoded as its not public
SomethingComplex map[string]Complex
}
答案2
得分: 1
你应该能够存储 json.RawMessage。请参考包文档中的示例。
RawMessage 是一个原始编码的 JSON 对象。它实现了 Marshaler 和 Unmarshaler 接口,可以用于延迟 JSON 解码或预先计算 JSON 编码。
它是一个 byte
切片,但如果你愿意,你可以很容易地将其转换为字符串。
英文:
You should be able to store the json.RawMessage. See the example in the package docs.
>RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.
It's a slice of byte
, but you can easily convert it to a string if you wish.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论