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

如何在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
    }
    
    已采纳该答案
    打赏 评论
  • dongyi1748 2018-04-05 10:46

    Simply encode each element of your slice individually:

    package main
    
    import (
            "encoding/json"
            "log"
            "os"
    )
    
    type T struct {
            ID          int    `json:"id"`
            Category    string `json:"category"`
            Name        string `json:"name"`
            Description string `json:"description"`
    }
    
    func main() {
            var data []T
    
            enc := json.NewEncoder(os.Stdout)
            for _, x := range data {
                    if err := enc.Encode(x); err != nil {
                            log.Fatal(err)
                    }
            }
    }
    
    打赏 评论

相关推荐 更多相似问题