Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

go - How to convert the dynamically produced array object data into JSON format string in golang?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...