dstobkpm908182 2018-04-05 10:20
浏览 338
已采纳

如何在golang中将动态生成的数组对象数据转换为JSON格式的字符串?

On the data retrieval the data is in the form of array object like this:

[{1 fruits Apple Apple is my favorite fruit.} {2 colors Red Red color is always charming.} {3 flowers Lotus It is one of the most beautiful flowers in this world.}]

how will I change it in JSON. I just need to break the array object braces [].

I have tried to Marshal it. But It gives me like:

[{"id":1,"category":"fruits","name":"Apple","description":"Apple is my favorite fruit."},{"id":2,"category":"colors","name":"Red","description":"Red color is always charming."},{"id":3,"category":"flowers","name":"Lotus","description":"It is one of the most beautiful flowers in this world."}]

The code I'd tried

Struct

type Item struct {
 Id          int    `json:"id"`
 Category    string `json:"category"`
 Name        string `json:"name"`
 Description string `json:"description"`
} 
type Items []Item

Here the function for retrieving data

func GetData(productQuery interface{}) (result Items, err error) {
 mongoSession := ConnectDb()
 sessionCopy := mongoSession.Copy()
 defer sessionCopy.Close()
 getCollection := mongoSession.DB("custom").C("custom")
 err = getCollection.Find(productQuery).Select(bson.M{"password": 0}).All(&result) //.Skip(skip).Limit(limit)
 if err != nil {
    return result, err
 }
 return result, nil
}
/*
 *
 *  Retrieve the data used by main function
 *
 *
 */

func retrieve(c *gin.Context) {
  conditions := bson.M{}
  data, err :=GetData(conditions)
  if err != nil {
    fmt.Println("There is somthing wrong")
  }
  fmt.Println("--------------------")
  fmt.Println(data)
  fmt.Println("--------------------")
  arrange(data)
  return
}   

func arrange(data Items) { 
  pagesJson, err := json.Marshal(data)
  if err != nil {
      log.Fatal("Cannot encode to JSON ", err)
  }
  fmt.Println(string(pagesJson))
}

I want to make the output like

{"id": 1,"category": "fruits","name": "Apple","description": "Apple is my favorite fruit."} {"id": 2,"category": "colors","name": "Red",description": "Red color is always charming."} {"id": 3,"category": "flowers","name": "Lotus","description": "It is one of the most beautiful flowers in this world."}

can anyone help me I tried it lot of times but don't take any success.

  • 写回答

2条回答 默认 最新

  • douzhan1963 2018-04-16 04:08
    关注

    This code will works

    package main
    
    import (
      "bytes"
      "encoding/json"
      "fmt"
      "log"
      "strings"
    )
    
    type Item struct {
      Id          int    `json:"id"`
      Category    string `json:"category"`
      Name        string `json:"name"`
      Description string `json:"description"`
    }
    
    type Items []Item
    
    var myJson = []byte(`[{
     "id":1,
     "category":"fruits",
     "name":"Apple",
     "description":"Apple is my favorite fruit."
    },
    {
     "id":2,
     "category":"colors",
     "name":"Red",
     "description":"Red color is always charming."
    },
    {
     "id":3,
     "category":"flowers",
     "name":"Lotus",
     "description":"It is one of the most beautiful flowers in this world."
    }]`)
    
    func main() {
        var items Items
    
        err := json.Unmarshal(myJson, &items)
        if err != nil {
         log.Fatal(err)
        }
    
        s, err := getMyString(items)
       if err != nil {
            log.Fatal(err)
       }
    
       fmt.Println(s)
    }
    
    func getMyString(items Items) (string, error) {
      var buffer bytes.Buffer
      var err error
      var b []byte
    
      for _, item := range items {
        b, err = json.Marshal(item)
        if err != nil {
            return "", err
        }
    
        buffer.WriteString(string(b) + " ")
      }
    
      s := strings.TrimSpace(buffer.String())
    
      return s, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误