downloadTemp2014
2018-09-12 18:05
浏览 516
已采纳

根据Golang中的对象值对JSON的解析进行排序

Trying to parse the json and sorting based on one of the values of struct. I want to sort the json based on the custom_meta's part_num, how we can do that. The code is as follows:

type Maininfo struct {
    Id   string     `json:"id"`
    Meta []Metainfo `json:"meta"`
}


type Metainfo struct {
    Filename     string `json:"filename"`
    Custom_meta  string `json:"custom_meta"`
    Size         int    `json:"size"`
    Content_hash string `json:"content_hash"`
}

type Custom_meta struct {
    Part_num string `json:"part_num"`
    Part     int
}

func getMeta(body []byte) (*Maininfo, error) {
    var s = new(Maininfo)
    err := json.Unmarshal(body, &s)
    if err != nil {
        fmt.Println("whoops:", err)
    }
    return s, err
}


func getMetainfo(body []byte) (*Metainfo, error) {
    var s = new(Metainfo)
    err := json.Unmarshal(body, &s)
    if err != nil {
        fmt.Println("error", err)
    }
    return s, err
}

type AxisSorter []Metainfo

func (a AxisSorter) Len() int           { return len(a) }
func (a AxisSorter) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a AxisSorter) Less(i, j int) bool { return a[i].Custom_meta < a[j].Custom_meta }


type NameSorter []Metainfo

func (a NameSorter) Len() int           { return len(a) }
func (a NameSorter) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a NameSorter) Less(i, j int) bool { return a[i].Custom_meta < a[j].Custom_meta }

func main() {
s, err := getMeta([]byte(body))
    fmt.Println("Main stuff", s)

    var metaInfo []Metainfo
    metaInfo = s.Meta
}
    var customMeta CustomMeta

    sort.Sort(AxisSorter(metaInfo))
    fmt.Println("metaInfo sorted ", metaInfo)

    sort.Sort(NameSorter(metaInfo))
    fmt.Println("metaInfo sorted 2 ", metaInfo)

    sort.Slice(metaInfo, func(i, j int) bool {
        fmt.Println("meta ", metaInfo[i].Custom_meta)
        return metaInfo[i].Custom_meta < metaInfo[j].Custom_meta
      })

}

I am not able to sort the code based on the part_num, how can we do that, since info is not a separate object it is a string. How we can parse string and sort it based on the int value.

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

1条回答 默认 最新

相关推荐 更多相似问题