假设JSON最初看起来像:
jsonData := {
"type": "text",
"contents": []
}
我想使用一个循环,以便在运行时将下面的json附加到contents
的jsonData
字段:
{
"type": "bubble",
"hero": {
"size": "full"
},
"body": {
"spacing": "sm",
"contents": [
{
"size": "xl"
},
{
"type": "box",
"contents": [
{
"flex": 0
},
{
"flex": 0
}
]
}
]
},
"footer": {
"spacing": "sm",
"contents": [
{
"type": "button",
"action": {
"type": "uri"
}
},
{
"type": "button",
"action": {
"type": "uri"
}
}
]
}
},
最后输出如下:
jsonData := {
"type": "text",
"contents": [{......},{.......}]
}
Golang是一种静态类型语言,与Javascript(JSON中的JS代表)不同。这意味着每个变量在编译时都必须具有指定的类型,这与JSON的工作方式不完全一致。
然而Golang提供了一个内置的json
包,简化了流程。
你应该知道在Go中使用JSON的3件事情,你可以推进更多...
[]interface{}
)map[string]interface{}
)json
包完成所有(json.Marshal
和json.Unmarshal
)我发现如果您阅读本文,您可以了解事情是如何运作的:
https://www.sohamkamani.com/blog/2017/10/18/parsing-json-in-golang/ https://blog.golang.org/json-and-go
package main
import (
"encoding/json"
"fmt"
)
//Member -
type Member struct {
Name string
Age int
Active bool
}
func main() {
// you data
mem := Member{"Alex", 10, true}
// JSON encoding
jsonBytes, err := json.Marshal(mem)
if err != nil {
panic(err)
}
// JSON to string for console
jsonString := string(jsonBytes)
fmt.Println(jsonString)
}
和“JSON和Go”文件https://blog.golang.org/json-and-go。