Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/json: Can json add newline between each elements in slice #42824

Closed
caoruidong opened this issue Nov 25, 2020 · 3 comments
Closed

encoding/json: Can json add newline between each elements in slice #42824

caoruidong opened this issue Nov 25, 2020 · 3 comments

Comments

@caoruidong
Copy link

caoruidong commented Nov 25, 2020

How can I write a slice to file in json format with new line between elements? Or only third party libs support it?

What did you expect to see?

a little compacter but still human readable

[
{"Name":"xx","Age":1},
{"Name":"test","Age":18}
]

or

[{"Name":"xx","Age":1},
{"Name":"test","Age":18}]

What did you see instead?

Marshal: not so human readable
[{"Name":"xx","Age":1},{"Name":"test","Age":18}]
MarshalIntent: too many lines, mostly more than one screen, low information density

[
{
"Name": "xx",
"Age": 1
},
{
"Name": "test",
"Age": 18
}
]
@jimen0
Copy link
Contributor

jimen0 commented Nov 25, 2020

Hi @caoruidong,

You can do it by using json.MarshalIndent. Here's an example: https://play.golang.org/p/VBxgYEd4BK5

package main

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

func main() {
	data := map[string]int{"a": 1, "b": 2}

	b, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s\n", b)
}

@martisch
Copy link
Contributor

Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.

For asking questions, see: https://github.com/golang/go/wiki/Questions

@caoruidong caoruidong changed the title encoding/json: Can json add newline between each elements in slice or map encoding/json: Can json add newline between each elements in slice Nov 26, 2020
@caoruidong
Copy link
Author

Thanks @jimen0 , do you have any ideas about slice?

@golang golang locked and limited conversation to collaborators Nov 26, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants