英文:
List of Go maps to Json
问题
你可以使用json.NewEncoder
来实现你想要的 JSON 文件格式。这个方法可以让你更加灵活地控制 JSON 的生成过程。下面是一个示例代码,展示了如何使用json.NewEncoder
来生成你期望的 JSON 文件格式:
package main
import (
"encoding/json"
"os"
)
func main() {
m := []map[string]interface{}{
{"a1": "aa1", "b1": "bb1"},
{"a2": "aa2", "b2": "bb2"},
{"a3": "aa3", "b3": "bb3"},
}
file, err := os.Create("file.json")
if err != nil {
panic(err)
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", "\t")
for _, item := range m {
err := encoder.Encode(item)
if err != nil {
panic(err)
}
}
}
这段代码会生成一个名为file.json
的文件,其中的内容符合你期望的格式。在这个格式中,每个 map 都会单独占据一行,没有[
和]
符号,也没有逗号分隔符。同时,每行的开头也没有空格缩进。
你可以根据需要修改代码中的变量名和文件名。希望这可以帮助到你!
英文:
I want to parse a list of maps in Go in a json file in a specific format. Following is the list that I have:
m := []map[string]interface{}{}
k1 := map[string]interface{}{"a1": "aa1", "b1": "bb1"}
k2 := map[string]interface{}{"a2": "aa2", "b2": "bb2"}
k3 := map[string]interface{}{"a3": "aa3", "b3": "bb3"}
m = append(m, k1, k2, k3)
This is how I parse it to a json file.
jsonFile, _ := json.MarshalIndent(m, "", "\t")
ioutil.WriteFile("file.json", jsonFile, os.ModePerm)
In the json file, I want:
- there to be no
[
or]
symbols at the beginning or end. - Each map to be in a new line
- there to be no comma between successive maps
- no space indentation at start of line.
This is how my json file looks at present:
[
{
"a1": "aa1",
"b1": "bb1"
},
{
"a2": "aa2",
"b2": "bb2"
},
{
"a3": "aa3",
"b3": "bb3"
}
]
Below is how I want the output in my saved json file to look:
{
"a1": "aa1",
"b1": "bb1"
}
{
"a2": "aa2",
"b2": "bb2"
}
{
"a3": "aa3",
"b3": "bb3"
}
I realize that I am able to have every map in a new line. So that is done. But, removal of [
or ]
symbols, commas after successive maps and indentation is yet to be done. How can I do this?
答案1
得分: 2
您的期望输出是一系列独立的JSON对象。使用json.Encoder
来逐个编码这些对象。
可以像这样实现:
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
for _, v := range m {
if err := enc.Encode(v); err != nil {
panic(err)
}
}
这将输出以下内容(在Go Playground上尝试):
{
"a1": "aa1",
"b1": "bb1"
}
{
"a2": "aa2",
"b2": "bb2"
}
{
"a3": "aa3",
"b3": "bb3"
}
此示例将JSON文本写入标准输出。如果要写入文件,请将os.Stdout
替换为*os.File
类型的文件值。
英文:
Your desired output is a series of independent JSON objects. Use a json.Encoder
to encode the objects individually.
Something like this:
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
for _, v := range m {
if err := enc.Encode(v); err != nil {
panic(err)
}
}
This will output (try it on the Go Playground):
{
"a1": "aa1",
"b1": "bb1"
}
{
"a2": "aa2",
"b2": "bb2"
}
{
"a3": "aa3",
"b3": "bb3"
}
This example writes the JSON text to the standard output. To log to a file, obviously pass an *os.File
value instead of os.Stdout
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论