1 回答

TA貢獻2080條經驗 獲得超4個贊
如果使用json.RawMessage
,JSON 源文本將不會被解析,而是按原樣存儲在其中(它是 a []byte
)。
因此,如果您想分發相同的 JSON 數組元素,則無需對其進行任何操作,您可以按原樣“移交”它。您不必將其傳遞給json.Marshal()
,它已經是 JSON 編組文本。
所以只需這樣做:
for _, input := range inputs.Foo { // input is of type json.RawMessage, and it's already JSON text }
如果您將 a 傳遞json.RawMessage
給json.Marshal()
,它可能會被重新編碼,例如壓縮(這可能會導致不同的字節序列,但它會保存與 JSON 相同的數據)。
壓縮甚至可能是一個好主意,因為從原始上下文(對象和數組)中取出原始縮進可能看起來很奇怪,而且它會更短。要簡單地壓縮 JSON 文本,您可以json.Compact()
這樣使用:
for _, input := range inputs.Foo {
buf := &bytes.Buffer{}
if err := json.Compact(buf, input); err != nil {
panic(err)
}
fmt.Println(buf) // The compacted array element value
}
如果您不想壓縮它,而是自己縮進數組元素,請json.Indent()像這樣使用:
for _, input := range inputs.Foo {
buf := &bytes.Buffer{}
if err := json.Indent(buf, input, "", " "); err != nil {
panic(err)
}
fmt.Println(buf)
}
使用您的示例輸入,這是第一個數組元素的樣子(原始、壓縮和縮進):
Orignal:
{
"id": "1234",
"someNestedObject": {
"someBool": true,
"randomNumber": 488
},
"timestamp": "2021-12-13T02:43:44.155Z"
}
Compacted:
{"id":"1234","someNestedObject":{"someBool":true,"randomNumber":488},"timestamp":"2021-12-13T02:43:44.155Z"}
Indented:
{
"id": "1234",
"someNestedObject": {
"someBool": true,
"randomNumber": 488
},
"timestamp": "2021-12-13T02:43:44.155Z"
}
試試Go Playground上的示例。
另請注意,如果您決定壓縮或縮進循環中的單個數組元素,您可以bytes.Buffer
在循環之前創建一個簡單的,并在每次迭代中重用它,調用它的Buffer.Reset()
方法來清除前一個數組的數據。
它可能看起來像這樣:
buf := &bytes.Buffer{}
for _, input := range inputs.Foo {
buf.Reset()
if err := json.Compact(buf, input); err != nil {
panic(err)
}
fmt.Println("Compacted:\n", buf)
}
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報