如何在Golang中格式化文本(txt)?

huangapple go评论84阅读模式
英文:

How to format a txt in golang?

问题

我有一个动态的 JSON,我将其转换为文本:JSON 的示例:

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

我转换它的代码如下:

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

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

我成功地将其转换为文本,但我需要给它一个特定的格式,只显示值而不显示标签,并按以下方式分隔:

luis | gomez | 87846516

我不知道如何给出这种格式。

英文:

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.

答案1

得分: 1

似乎你正在从数据库获取数据,然后将其保存到文本文件中。最好的方法是从数据库获取数据,然后简单地循环遍历每一行。不清楚为什么问题是将json数据转换,如果它可以从数据库中获取。与其将其转换为json,直接将值写入文件。

你可以打开一个文件,使每个条目都会被追加,然后在完成文件操作后关闭文件。我提供了一个示例文件,无论返回的行数(我假设每个来自数据库的行都是新行)或列数,都可以给你所需的输出。

下面的代码经过测试,输出为:luis | gomez | 87846516

OS.APPEND将每次写入时追加一个新行。因此,如果你多次运行此代码,它不会覆盖文件,而是添加到文件中。

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
}
英文:

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
}
</details>
# 答案2
**得分**: 0
首先创建一个名为`Person`的结构体对象,然后定义一个`String`函数来实现你想要的功能。
```go
package main
import (
"encoding/json"
"strconv"
)
type Person struct {
Name     string `json:"name"`
LastName string `json:"last_name"`
IdNumber int    `json:"id_number"`
}
// 以 " | " 为分隔符转换为csv格式
func (p Person) String() string {
return p.Name + " | " + p.LastName + " | " + strconv.Itoa(p.IdNumber)
}
func main() {
// json数据
jsonData := map[string]interface{}{
"name":      "luis",
"last_name": "gomez",
"id_number": 87846516,
}
person := Person{}
jsonDataByte, _ := json.Marshal(jsonData)
json.Unmarshal(jsonDataByte, &person)
// 打印person
println(person.String())
}

答案是:

luis | gomez | 87846516
英文:

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

package main
import (
&quot;encoding/json&quot;
&quot;strconv&quot;
)
type Person struct {
Name     string `json:&quot;name&quot;`
LastName string `json:&quot;last_name&quot;`
IdNumber int    `json:&quot;id_number&quot;`
}
// Convert to csv separated by &quot; | &quot;
func (p Person) String() string {
return p.Name + &quot; | &quot; + p.LastName + &quot; | &quot; + strconv.Itoa(p.IdNumber)
}
func main() {
// json data
jsonData := map[string]interface{}{
&quot;name&quot;:      &quot;luis&quot;,
&quot;last_name&quot;: &quot;gomez&quot;,
&quot;id_number&quot;: 87846516,
}
person := Person{}
jsonDataByte, _ := json.Marshal(jsonData)
json.Unmarshal(jsonDataByte, &amp;person)
// print person
println(person.String())
}

The answer is:

luis | gomez | 87846516

huangapple
  • 本文由 发表于 2021年11月19日 06:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/70027680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定