Home > database >  How to format a txt in golang?
How to format a txt in golang?

Time:11-19

I have a json which is dynamic and that I convert to txt: EXAMPLE OF THE JSON:

   {name: luis, last name: gomez, id_number: 87846516}

code where I convert it is like this:

    file, _: = json.MarshalIndent (string (jsonData), "", "")

    data: = ioutil.WriteFile ("test.txt", file, 0644)

I convert it to txt successfully but I need to give it a specific format in which only the values ​​appear without labels and separated as follows:

     luis | gomez | 87846516

The format I do not know how to give it.

CodePudding user response:

It seems that you are getting data from a data base and then saving it to a text file. The best way would be to get the data from the database and then simply loop through each row. It is unclear why the question is posed as converting json data if it is available from a database. Rather than converting it to json, write the values to a file directly.

You can open a file so that each entry will be appended and then close when done with the file. I have provided a sample file that will give you the output desired regardless of number of rows returned (I assumed it would be a new line for each row from the data base) or the number of columns.

The below code was tested and prints: luis | gomez | 87846516

The OS.APPEND will append a new line each time it writes. So if you run this code multiple times, it will not overwrite it but add to the file.

package main

import (
    "database/sql"
    "fmt"
    "log"
    "os"
    "strings"

    _ "github.com/go-sql-driver/mysql"
)

type DbDao struct {
    db *sql.DB
}

var db DbDao

func (d *DbDao) Init(connstr string) error {

    db, err := sql.Open("mysql", connstr)
    if err != nil {
        return err
    }
    err = db.Ping()
    if err != nil {
        return err
    }
    d.db = db
    return nil
}

func main() {

    dblogin := os.Getenv("DBLOGIN")
    dbString := fmt.Sprintf("root:%s@/testDB", dblogin)
    err := db.Init(dbString)
    if err != nil {
        log.Fatal("Failed to create db connection:", err.Error())
    }

    f, err := os.OpenFile("text.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
    if err != nil {
        log.Fatalf("ERROR: error opening file: %v", err)
    }
  defer f.Close()

    queryText := "select * from stackOverflow"
    rows, err := db.db.Query(queryText)
    if err != nil {
        log.Fatal(err)
    }

    columns, err := rows.Columns()
    if err != nil {
        log.Fatal(err)
    }

    count := len(columns)
    values := make([]interface{}, count)
    scanArgs := make([]interface{}, count)
    for i := range values {
        scanArgs[i] = &values[i]
    }

    for rows.Next() {
        err := rows.Scan(scanArgs...)
        if err != nil {
            log.Fatal(err)
        }

        concat := make([]string, 0)
        for i, _ := range columns {
            v := values[i]

            b, ok := v.([]byte)
            if ok {
                concat = append(concat, string(b))
            } else {
                concat = append(concat, fmt.Sprintf("%v", v))
            }
        }
        line := strings.Join(concat, " | ")
        fmt.Println(line)
        _, err = f.Write([]byte(fmt.Sprintf("%s\n", line)))
        if err != nil {
            log.Fatal(err)
        }

    }

    return
}

CodePudding user response:

First create struct object called Person, then define a String function to do what you want

package main

import (
    "encoding/json"
    "strconv"
)

type Person struct {
    Name     string `json:"name"`
    LastName string `json:"last_name"`
    IdNumber int    `json:"id_number"`
}

// Convert to csv separated by " | "
func (p Person) String() string {
    return p.Name   " | "   p.LastName   " | "   strconv.Itoa(p.IdNumber)
}

func main() {

    // json data
    jsonData := map[string]interface{}{
        "name":      "luis",
        "last_name": "gomez",
        "id_number": 87846516,
    }

    person := Person{}
    jsonDataByte, _ := json.Marshal(jsonData)
    json.Unmarshal(jsonDataByte, &person)

    // print person
    println(person.String())
}

The answer is:

luis | gomez | 87846516
  •  Tags:  
  • go
  • Related