我正在编写一个简单的post api请求。我能够将JSON解析为golang结构直至对等名称json对象。我不知道通过将值传递到api的JSON主体来填充结构的golang切片的正确语法。
我正在尝试解析通过api发送的JSON正文。这是示例正文请求-
{
"type":"string",
"name":"string",
"organization":{
"orgID":"1",
"orgName":"string",
"peer":{
"peerID":"1",
"peerName":"string"
},
"attributes":[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
} "peerName":"string"
},
"attributes":["name":"string":"value":true]
}
}
这是我的示例golang结构。
//Identity ...
type Identity struct {
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
Organization *Organization `json:"organization,omitempty"`
}
//Organization ....
type Organization struct {
OrgID string `json:"orgID,omitempty"`
OrgName string `json:"orgName,omitempty"`
Peer *Peer `json:"peer,omitempty"`
Attributes *Attributes `json:"attributes"`
}
//Peer ...
type Peer struct {
PeerID string `json:"peerID,omitempty"`
PeerName string `json:"peerName,omitempty"`
}
//Attributes ...
type Attributes []struct {
Name string `json:"name"`
Value bool `json:"value"`
}
答案 0 :(得分:0)
最后弄清楚了正确的语法。我们必须通过JSON传递结构数组。
{
"type":"string",
"name":"string",
"organization":
{
"orgID":"1",
"orgName":"string",
"peer":
{
"peerID":"1",
"peerName":"string"
},
"attributes":
[
{"slide0001.html": "Looking Ahead"},
{"slide0008.html": "Forecast"},
{"slide0021.html": "Summary"}
]
}
}
答案 1 :(得分:0)
您可以在UnmarshalJSON
函数中做任何您想做的事情。
您可以获得输出:{A:[{Name:slide0001.html Value:Looking Ahead} {Name:slide0008.html Value:Forecast} {Name:slide0021.html Value:Summary}]}
var (
jso = []byte(`
{
"attributes":
[
{"slide0001.html": "Looking Ahead"},
{"slide0008.html": "Forecast"},
{"slide0021.html": "Summary"}
]
}`)
)
type B struct {
A As `json:"attributes"`
}
type As []A
type A struct {
Name string
Value string
}
func (as *As) UnmarshalJSON(data []byte) error {
var attr []interface{}
if err := json.Unmarshal(data, &attr); err != nil {
return err
}
if len(attr) > 0 {
newAs := make([]A, len(attr))
// i := 0
for i, val := range attr {
if kv, ok := val.(map[string]interface{}); ok && len(kv) > 0 {
for k, v := range kv {
a := A{
Name: k,
Value: v.(string),
}
newAs[i] = a
i++
break
}
}
}
*as = newAs
}
return nil
}