将 JSON 对象“原样”存储到数据存储中。

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

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.

huangapple
  • 本文由 发表于 2014年3月18日 18:12:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/22476174.html
匿名

发表评论

匿名网友

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

确定