简体   繁体   English

如何通过 json 将键值对数组传递给结构体的 golang 切片

[英]How do I pass array of key,value pairs to golang slice of struct through json

I am writing a simple post api request.我正在写一个简单的 post api 请求。 I am able to parse the JSON into golang structs upto the peername json object.我能够将 JSON 解析为 golang 结构,直到 peername json 对象。 I do not know the correct syntax to populate a golang slice of a struct by passing values through the JSON body of the api.我不知道通过 api 的 JSON 主体传递值来填充结构的 golang 切片的正确语法。

I am trying to parse JSON body sent through an api.我正在尝试解析通过 api 发送的 JSON 正文。 This is the sample body request -这是示例正文请求 -

{  
   "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]
        }
    }

And this is my sample golang structs.这是我的示例 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"`
}

Finally figured out the correct syntax.终于想出了正确的语法。 We have to pass an array of structs through JSON.我们必须通过 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"}
      ]
    }
}

you can do whatever you want in a UnmarshalJSON Function.你可以在UnmarshalJSON函数中做任何你想做的事情。

i made an example in playground.我在操场上做了一个例子。 https://play.golang.org/p/WY6OCR8K3Co https://play.golang.org/p/WY6OCR8K3Co

you can get output: {A:[{Name:slide0001.html Value:Looking Ahead} {Name:slide0008.html Value:Forecast} {Name:slide0021.html Value:Summary}]}你可以得到输出: {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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM