dtqysxw4659 2016-11-23 16:36
浏览 82

如何将hit.source反序列化为golang中的结构

i have been using this repository:

https://github.com/olivere/elastic

The next code is a example of elasticsearch query in golang :

  searchResult, err := client.Search().
      Index("mx").
      Type("postal_code").
      Source(searchJson).
      Pretty(true). 
      Do()
  if err != nil {
      panic(err)
  }

  if searchResult.Hits.TotalHits > 0 {

    for _, hit := range searchResult.Hits.Hits {
      var d Document
      err := json.Unmarshal(*hit.Source, &d)
      if err != nil {
        // Deserialization failed
      }

      fmt.Printf("Document by %s: %s
", d.Colonia, d.Ciudad)

    }

  } else {
    fmt.Print("Found no documents
")
  }

this works fine, the out is something like this:

Document by Villa de Cortes: Distrito Federal
Document by Villa de Cortes: Sinaloa
Document by Villa de Cortes: Sinaloa

But i need the out like json array, something like this:

[
  {

      "cp": "03530",
      "colonia": "Villa de Cortes",
      "ciudad": "Distrito Federal",
      "delegacion": "Benito Juarez",
      "location": {
        "lat": "19.3487",
        "lon": "-99.166"
      }
  },
  {

      "cp": "81270",
      "colonia": "Villa de Cortes",
      "ciudad": "Sinaloa",
      "delegacion": "Ahome",
      "location": {
        "lat": "25.1584",
        "lon": "-107.7063"
      }
  },
  {
      "cp": "80140",
      "colonia": "Villa de Cortes",
      "ciudad": "Sinaloa",
      "delegacion": "Culiacan",
      "location": {
        "lat": "25.0239",
        "lon": "-108.032"
      }
  }
]

How can i to deserialize hit.Source into a Document struct?

type Document struct {
  Ciudad     string `json:"ciudad"`
  Colonia    string `json:"colonia"`
  Cp         string `json:"cp"`
  Delegacion string `json:"delegacion"`
  Location   struct {
    Lat string `json:"lat"`
    Lon string `json:"lon"`
  } `json:"location"`
}

Here is the full source code of the script:

https://gist.github.com/hectorgool/67730c8a72f2d34b09e5a8888987ea0c

  • 写回答

2条回答 默认 最新

  • douhuo1738 2016-11-23 18:07
    关注

    Well, you are Unmarshalling your data into the document struct, if you want to print it as raw json you can simply Marshal it again, so only the tags you specified in your Document struct are show.

    If you want the output to be a json array, just store all your Documents into a slice and then Marshal the whole thing

    var documents []Document
    for (...) {
        (...)
        documents = append(documents, d)
    }
    
    rawJsonDocuments, err := json.Marshal(documents)
    fmt.Printf("%v", string(rawJsonDocuments) )
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入