How to convert the array object data to string format data using golang?

Puneet :

There is an array object which is retrieved from mongodb. The data looks like below:-

[{
  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.
 }]

This is the code for retrieving the above data The struct is:

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

func GetData(Query interface{}) (result Items, err error) {
    mongoSession := ConnectDb()
    sessionCopy := mongoSession.Copy()
    defer sessionCopy.Close()
    getCollection := mongoSession.DB("custom").C("custom")
    err = getCollection.Find(Query).All(&result)
    if err != nil {
        return result, err
    }
    return result, nil
}
/*
 *  Retrieve the data used by main function
 */
func retrieve(c *gin.Context) {
  //mongoSession := ConnectDb()
  conditions := bson.M{}
  data, err :=GetData(conditions)
  if err != nil {
    fmt.Println("There is somthing wrong")
  }
  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))
}

Running json.Marshal, the output looks like below:

[{
  "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."
}]

Expected output

{
  "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 issue is the data is in the array object for my use I need the String structure data between {} as shown above. I posted this question before but not getting any success answer. I am trying it from a lot of time help me thankyou.

sf9v :

Based on what OP has discussed, marshaling the struct Items would give this:

[{
  "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."
}]

From this, OP wants to get a string that looks like this:

{
  "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."
}

There are two approaches that I considered:

  1. Looping through items and appending each marshaled items into a string (clearly not efficient)

    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())
        // trim last comma
        s = s[:len(s)-1]
    
        return s, nil
    }
    
  2. Or just trimming off the leading and trailing square brackets:

    func getMyString2(items Items) (string, error) {
    
        b, err := json.Marshal(items)
        if err != nil {
            return "", err
        }
    
        s := string(b)
        s = strings.TrimSpace(s)
        // trim leading and trailing spaces
        s = s[1 : len(s)-1]
        return s, nil
    }
    

Link to code: https://play.golang.org/p/F1SUYJZEn_n

EDIT: Since OP want it to be space separated, I've modified approach number 1 to fit the requirements:

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
        }
        // use space to separate each json string in the array
        buffer.WriteString(string(b) + " ")
    }

    s := strings.TrimSpace(buffer.String())

    return s, nil
}

Link to new code: https://play.golang.org/p/dVvsQlsRqZO

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

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

How to convert a string to an array in Golang?

How to convert the data to json format using Laravel

How to get data in string array or JSON format using linq to entities?

How to convert an object to a string with a format string?

Convert serialized data to array or object

Convert data format using awk?

How to convert data format in JSON using SED

How to convert string data with variable format to datetime?

How convert Object String to Data Class in kotlin

Get API Json data in object and array format using redux and reactjs

How do I convert data from html table into array of object using vanilla javascript

Convert to list of data class object from JSON string using Gson?

Format array of data to object

Convert Data format using SimpleDateFormat

How to convert the string type data into date format in postgres?

how to convert arraylist data to string array in android

How to convert array format but non-array data into an array in PHP?

How convert array data to object array?

Convert string to hex array data

how do i convert data table date to a certain string format

How to convert list of Object into Specified format String using JS

Convert Data Object to array of structs

How to post data as an array object using axios

How to convert an azure data factory string type variable into datetime format

Convert a decimal array to string format in golang

How do I convert a data table to this JSON object format in R?

How to convert an array object into object data in a specific format

How can I convert a string containing data in a specific format into an array of associative arrays in PHP?