2018-06-04 02:32
浏览 33


I have to unmarshal a series of Json objects, but one of the objects contain a json array which is not really structured in a good way.

"labels": [
      "key": "owner",
      "value": "harry"
      "key": "group",
      "value": "student"

I am unmarshalling it using this struct -

type StudentDetails struct {
Id        string         `json:"id"`
Name      string         `json:"name"`
Labels    []Label   `json:"labels,omitempty"`
type Label struct {
Key string `json:"key"`
Value string `json:"value"`

And I have to access it using x.Labels[0].key == "owner" inside a for loop which is very annoying. I want to be able to do x.Labels.Owner == "harry" instead. How do I go about achieving this? The rest of JSON is unmarshalled fine using the default unmarshal function, so I don't think writing custom function will be good option.

图片转代码服务由CSDN问答提供 功能建议


 “ labels”:[
“ key”:“所有者”,
“ value”:“ harry” 
“ key”:“ group”,
“ value”:“ student” 

我正在使用以下方法将其解组 此结构-

  type StudentDetails结构{
Id字符串json:“ id”`
名称字符串json:“ name”`
Labels [] Label`json:“  labels,omitempty“`
type Label struct {
密钥字符串`json:” key“`
值字符串`json:” value“`

我必须使用x.Labels [0] .key ==“ owner”在一个for循环中访问它,这很烦人。 我希望能够执行x.Labels.Owner ==“ harry”。 我该如何实现这一目标? 使用默认的unmarshal函数可以很好地解组JSON的其余部分,因此我认为编写自定义函数不是一个好选择。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题