Home > Back-end >  How i can put a comma a the end every time i write a file?
How i can put a comma a the end every time i write a file?

Time:03-04

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

CodePudding user response:

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

CodePudding user response:

    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.

CodePudding user response:

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, "", "  ")

}
  •  Tags:  
  • go
  • Related