每次写入文件时,我如何在末尾添加逗号?

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

How i can put a comma a the end every time i write a file?

问题

我有一个JSON文件,它接收一个以JSON格式表示的地图,同一个文件多次接收不同的地图。问题是每次写入文件时,每个对象的末尾都缺少逗号,我该如何在每个写入的对象末尾添加逗号?

这是我正在使用的代码:

b, _ := json.MarshalIndent(user, "", "  ")
// 将JSON写入文件
_ = ioutil.WriteFile(nameFile, b, 0644)

// 追加到文件
// 如果文件不存在,则使用O_CREATE创建文件,设置文件为读写模式,添加追加标志并设置权限
f, err := os.OpenFile("/Users/re-process/"+nameFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
if err != nil {
    log.Fatal(err)
}
// 写入文件,f.Write()
f.Write(b)

这是我得到的输出:

{
  "name": "jhon",
  "tittle": "grant"
}{
  "name": "jhon",
  "tittle": "grant"
}

这是期望的输出:

{
  "name": "jhon",
  "tittle": "grant"
},
{
  "name": "jhon2",
  "tittle": "grant2"
}
英文:

I have a json file thats recibe a map formatted as a json, the same file recibe multiple times differents maps, the problem thats occurred is every time i write the file is missing the comma at the end of every object, how i can put a comma at the end of every object written?

This is the code im using:

b, _ := json.MarshalIndent(user, "", "  ")
	// writing json to file
	_ = ioutil.WriteFile(nameFile, b, 0644)

	// to append to a file
	// create the file if it doesn't exists with O_CREATE, Set the file up for read write, add the append flag and set the permission
	f, err := os.OpenFile("/Users/re-process/"+nameFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
	if err != nil {
		log.Fatal(err)
	}
	// write to file, f.Write()
	f.Write(b)

this is the output i got:

{
  "name": "jhon",
  "tittle": "grant"
}{
  "name": "jhon",
  "tittle": "grant"
}

and this is the expected output:

{
  "name": "jhon",
  "tittle": "grant"
},
{
  "name": "jhon2",
  "tittle": "grant2"
}

答案1

得分: 1

你好,以下是代码的翻译:

type User struct {
    Name   string `json:"name"`
    Tittle string `json:"tittle"`
}

func main() {
    user := User{Name: "jhon", Tittle: "grant"}
    user2 := User{Name: "Jhon", Tittle: "Grant"}
    users := []User{user, user2}
    //b, _ := json.Marshal(users) // 得到相同的结果,但你需要自己美化 JSON。
    b, _ := json.MarshalIndent(users, "", "  ")
    nameFile := "article.json"
    _ = ioutil.WriteFile(nameFile, append(b), 0644)
}

json.MarshalIndent函数可以完成你的需求,你不需要显式地插入逗号,因为这似乎是一个"User"对象的数组。

英文:
    type User struct {
	Name   string `json:"name"`
	Tittle string `json:"tittle"`
}

func main() {
	user := User{Name: "jhon", Tittle: "grant"}
	user2 := User{Name: "Jhon", Tittle: "Grant"}
	users := []User{user, user2}
	//b, _ := json.Marshal(users) // Gets you the same result, but you will have to pretty the Json yourself.
	b, _ := json.MarshalIndent(users, "", "  ")
	nameFile := "article.json"
	_ = ioutil.WriteFile(nameFile, append(b), 0644)

}

json Marshaler does the job you, don't have to insert the "," explicitly, because after all this seems to be an array of "User" objects.

答案2

得分: 1

听起来你正在尝试将来自不同来源的JSON文档合并,然后将它们写入文件。我建议将它们全部合并成一个JSON,然后一次性写入文件,而不是分别将每个来源写入文件,然后追加到文件中。

这种方法可以确保最终的JSON文档是有效的。

package main

import (
	"encoding/json"
	"log"
	"os"
)

var (
	m1 = json.RawMessage(`[{"name":"bob","title":"Mr."},{"name":"bob2","title":"Mr.2"}]`)
	m2 = json.RawMessage(`[{"name":"bob3","title":"Mr.3"},{"name":"bob4","title":"Mr.4"}]`)
	m3 = json.RawMessage(`[{"name":"bob5","title":"Mr.5"},{"name":"bob6","title":"Mr.6"}]`)
)

func main() {

	result, err := mergeJSON(m1, m2, m3)
	if err != nil {
		log.Fatal(err)
	}

	f, err := os.OpenFile("file.json", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
	if err != nil {
		log.Fatal(err)
	}
	f.Write(result)
}

func mergeJSON(j ...json.RawMessage) (json.RawMessage, error) {

	var m []interface{}

	for _, v := range j {
		var d interface{}
		json.Unmarshal(v, &d)

		b := d.([]interface{})
		m = append(m, b...)
	}

	return json.MarshalIndent(m, "", "  ")

}

希望对你有帮助!

英文:

It sounds like you are trying to combine json documents from various sources and then write them to a file. I would combine all of them into one json and write it to the file once rather than writing each source to file separately and then appending the file.

This method will ensure the final json document is valid.

package main

import (
	"encoding/json"
	"log"
	"os"
)

var (
	m1 = json.RawMessage(`[{"name":"bob","title":"Mr."},{"name":"bob2","title":"Mr.2"}]`)
	m2 = json.RawMessage(`[{"name":"bob3","title":"Mr.3"},{"name":"bob4","title":"Mr.4"}]`)
	m3 = json.RawMessage(`[{"name":"bob5","title":"Mr.5"},{"name":"bob6","title":"Mr.6"}]`)
)

func main() {

	result, err := mergeJSON(m1, m2, m3)
	if err != nil {
		log.Fatal(err)
	}

	f, err := os.OpenFile("file.json", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
	if err != nil {
		log.Fatal(err)
	}
	f.Write(result)
}

func mergeJSON(j ...json.RawMessage) (json.RawMessage, error) {

	var m []interface{}

	for _, v := range j {
		var d interface{}
		json.Unmarshal(v, &d)

		b := d.([]interface{})
		m = append(m, b...)
	}

	return json.MarshalIndent(m, "", "  ")

}

答案3

得分: 0

package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
)

type User struct {
	Name   string `json:"name"`
	Tittle string `json:"tittle"`
}

func main() {
	user := User{Name: "jhon", Tittle: "grant"}
	b, _ := json.MarshalIndent(user, "", "  ")
	nameFile := "article.json"

	_ = ioutil.WriteFile(nameFile, append(b, ','), 0644)

	f, err := os.OpenFile(nameFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
	if err != nil {
		log.Fatal(err)
	}
	f.Write(b)
}

看起来你想要翻译的是一段Go语言的代码。这段代码创建了一个名为User的结构体,其中包含NameTittle两个字段。然后,代码将一个User对象序列化为JSON格式,并将其写入名为article.json的文件中。最后,代码将JSON数据追加到文件末尾,并将其写入文件。

英文:
package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
)

type User struct {
	Name   string `json:"name"`
	Tittle string `json:"tittle"`
}

func main() {
	user := User{Name: "jhon", Tittle: "grant"}
	b, _ := json.MarshalIndent(user, "", "  ")
	nameFile := "article.json"

	_ = ioutil.WriteFile(nameFile, append(b, ','), 0644)

	f, err := os.OpenFile(nameFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
	if err != nil {
		log.Fatal(err)
	}
	f.Write(b)
}

It seems that.

enter image description here

huangapple
  • 本文由 发表于 2022年3月3日 11:46:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/71331915.html
匿名

发表评论

匿名网友

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

确定