[Solved] How to convert the dynamically produced array object data into JSON format string in golang?


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
}

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