我如何在切片内进行json解组切片

时间:2018-08-22 22:47:46

标签: json go

我试图解组一些非常丑陋的json,但不知道如何处理。我有:

package main

import "fmt"
import "encoding/json"

type PublicKey struct {
    ID     int    `json:"id"`
    Key    string `json:"key"`
    MyData []struct {
        ID    string `json:"id"`
        Value int    `json:"value"`
    }
}

func main() {
    b := `[
  {
    "id": 1,
    "key": "my_key"
  },
  [
    {
      "id": "some_id",
      "value": 12
    },
    {
      "id": "anorther_id",
      "value": 13
    }
  ]
]`

    var pk []PublicKey
    err := json.Unmarshal([]byte(b), &pk)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(pk)

}

对于结果,我得到了:

[{1 my_key []} {0  []}]

第二个分片不应为空。

编辑: 我得到的错误是:

json: cannot unmarshal array into Go struct field PublicKey.key of type main.PublicKey

https://play.golang.org/p/cztXOchiiS5

2 个答案:

答案 0 :(得分:1)

那是一些真正可怕的JSON!我有两种处理混合数组元素的方法,我更喜欢第二种方法。这是使用interface和类型开关的第一种方法:

package main

import (
    "encoding/json"
    "errors"
    "fmt"
)

type PublicKey struct {
    ID  int    `json:"id"`
    Key string `json:"key"`
}

type MyData struct {
    ID    string `json:"id"`
    Value int    `json:"value"`
}

type MixedData struct {
    Key    []PublicKey
    MyData [][]MyData
}

func (md *MixedData) UnmarshalJSON(b []byte) error {
    md.Key = []PublicKey{}
    md.MyData = [][]MyData{}
    var obj []interface{}
    err := json.Unmarshal([]byte(b), &obj)
    if err != nil {
        return err
    }
    for _, o := range obj {
        switch o.(type) {
        case map[string]interface{}:
            m := o.(map[string]interface{})
            id, ok := m["id"].(float64)
            if !ok {
                return errors.New("public key id must be an int")
            }
            pk := PublicKey{}
            pk.ID = int(id)
            pk.Key, ok = m["key"].(string)
            if !ok {
                return errors.New("public key key must be a string")
            }
            md.Key = append(md.Key, pk)
        case []interface{}:
            a := o.([]interface{})
            myData := make([]MyData, len(a))
            for i, x := range a {
                m, ok := x.(map[string]interface{})
                if !ok {
                    return errors.New("data array contains unexpected object")
                }
                val, ok := m["value"].(float64)
                if !ok {
                    return errors.New("data value must be an int")
                }
                myData[i].Value = int(val)
                myData[i].ID, ok = m["id"].(string)
                if !ok {
                    return errors.New("data id must be a string")
                }
                md.MyData = append(md.MyData, myData)
            }
        default:
            // got something unexpected, handle somehow
        }
    }
    return nil
}

func main() {
    b := `[
  {
    "id": 1,
    "key": "my_key"
  },
  [
    {
      "id": "some_id",
      "value": 12
    },
    {
      "id": "another_id",
      "value": 13
    }
  ]
]`

    m := MixedData{}
    err := json.Unmarshal([]byte(b), &m)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(m)

}

https://play.golang.org/p/g8d_AsH-pYY

希望没有任何意外的其他元素,但是可以类似地处理它们。

这是第二个在json.RawMessage的帮助下更加依赖Go的内部JSON解析的方法。它对数组的内容做出相同的假设。它假定任何对象将解组到PublicKey实例中,并且任何数组仅由MyData实例组成。我还添加了如何编组回目标JSON以实现对称性:

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

type PublicKey struct {
    ID  int    `json:"id"`
    Key string `json:"key"`
}

type MyData struct {
    ID    string `json:"id"`
    Value int    `json:"value"`
}

type MixedData struct {
    Keys   []PublicKey
    MyData [][]MyData
}

func (md *MixedData) UnmarshalJSON(b []byte) error {
    md.Keys = []PublicKey{}
    md.MyData = [][]MyData{}
    obj := []json.RawMessage{}
    err := json.Unmarshal([]byte(b), &obj)
    if err != nil {
        return err
    }
    for _, o := range obj {
        switch o[0] {
        case '{':
            pk := PublicKey{}
            err := json.Unmarshal(o, &pk)
            if err != nil {
                return err
            }
            md.Keys = append(md.Keys, pk)
        case '[':
            myData := []MyData{}
            err := json.Unmarshal(o, &myData)
            if err != nil {
                return err
            }
            md.MyData = append(md.MyData, myData)
        default:
            // got something unexpected, handle somehow
        }
    }
    return nil
}

func (md *MixedData) MarshalJSON() ([]byte, error) {
    out := make([]interface{}, len(md.Keys)+len(md.MyData))
    i := 0
    for _, x := range md.Keys {
        out[i] = x
        i++
    }
    for _, x := range md.MyData {
        out[i] = x
        i++
    }
    return json.Marshal(out)
}

func main() {
    b := `[
  {
    "id": 1,
    "key": "my_key"
  },
  [
    {
      "id": "some_id",
      "value": 12
    },
    {
      "id": "another_id",
      "value": 13
    }
  ]
]`

    m := MixedData{}
    err := json.Unmarshal([]byte(b), &m)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(m)

    enc := json.NewEncoder(os.Stdout)
    enc.SetIndent("", "    ")
    if err := enc.Encode(m); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

https://play.golang.org/p/ryZzaWKNcN0

答案 1 :(得分:1)

这是一种结合json.RawMessage和在创建json.Unmarshaler的类型中使用默认unmarshaler的技巧,方法是创建一个新的临时类型作为目标类型的别名。

这个想法是我们将传入的数组解组为原始消息,并确保数组长度符合我们的期望。然后,我们使用其JSON标签注释将各个数组元素解组为自定义结构类型。最终结果是,我们可以用通常的方式来解组PublicKey类型,一旦您理解了窍门,就很难遵循UnmarshalJSON代码。

例如(Go Playground):

type PublicKey struct {
  ID   int    `json:"id"`
  Key  string `json:"key"`
  Data []MyData
}

type MyData struct {
  ID    string `json:"id"`
  Value int    `json:"value"`
}

func (pk *PublicKey) UnmarshalJSON(bs []byte) error {
  // Unmarshal into a RawMessage so we can inspect the array length.
  var rawMessage []json.RawMessage
  err := json.Unmarshal(bs, &rawMessage)
  if err != nil {
    return err
  }
  if len(rawMessage) != 2 {
    return fmt.Errorf("expected array of length 2, got %d", len(rawMessage))
  }

  // Parse the first object as PublicKey using the default unmarshaler
  // using a temporary type that is an alias for the target type.
  type PublicKey2 PublicKey
  var pk2 PublicKey2
  err = json.Unmarshal(rawMessage[0], &pk2)
  if err != nil {
    return err
  }

  // Parse the second object as []MyData in the usual way.
  err = json.Unmarshal(rawMessage[1], &pk2.Data)
  if err != nil {
    return err
  }

  // Finally, assign the aliased object to the target object.
  *pk = PublicKey(pk2)
  return nil
}

func main() {
  var pk PublicKey
  err := json.Unmarshal([]byte(jsonstr), &pk)
  if err != nil {
    panic(err)
  }
  fmt.Printf("%#v\n", pk)
  // main.PublicKey{ID:1, Key:"my_key", Data:[]main.MyData{main.MyData{ID:"some_id", Value:12}, main.MyData{ID:"anorther_id", Value:13}}}

}