我有一個 json 檔案,它是一個格式化為 json 的地圖,同一個檔案 recibe 多次不同的地圖,發生的問題是每次我寫檔案時都缺少每個物件末尾的逗號,我怎么能放一個每個寫入物件末尾的逗號?
這是我使用的代碼:
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)
這是我得到的輸出:
{
"name": "jhon",
"tittle": "grant"
}{
"name": "jhon",
"tittle": "grant"
}
這是預期的輸出:
{
"name": "jhon",
"tittle": "grant"
},
{
"name": "jhon2",
"tittle": "grant2"
}
uj5u.com熱心網友回復:
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 可以完成您的作業,不必顯式插入“,”,因為畢竟這似乎是“用戶”物件的陣列。
uj5u.com熱心網友回復:
聽起來您正在嘗試組合來自各種來源的 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, "", " ")
}
uj5u.com熱心網友回復:
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)
}
看起來。
在此處輸入影像描述
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/438864.html
標籤:走
