json - 如何将标头添加到 JSON 以识别数组值的数组名称
问题描述
我正在尝试查看是否有一种方法(简单的方法)可以使用encoding/json
GO 向 JSON 中的每个数组添加标头。
我的意思是说?
想要有这样的东西:
{
"Dog":[
{
"breed":"Chihuahua",
"color":"brown"
},
{
"breed":"Pug",
"color":"white"
}
],
"Cat":[
{
"breed":"British",
"color":"white"
},
"breed":"Ragdoll",
"color":"gray"
}
]
}
主要思想是在这种情况下有一个“类别”Dog
并且Cat
.
我已经有了这个解决方案,但我正在寻找可以改进它的东西。
我的代码如下所示:
type Dog struct {
Breed string
Color string
}
type Cat struct {
Breed string
Color string
}
func main(){
dogs := [...]Dog{
{"Chihuahua", "brown"},
{"Pug", "white"},
}
cats := [...]Cat{
{"British", "white"},
{"Ragdoll", "gray"},
}
c, err := json.MarshalIndent(cats, "", "\t")
if err != nil {
log.Fatal(err)
}
d, err := json.MarshalIndent(dogs, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Println("{")
fmt.Printf(" \"Dog\": %v,\n", string(d))
fmt.Printf(" \"Cat\": %v\n}", string(c))
}
主要思想是将“Dog”和“Cat”作为新数组,但我想改进我的代码以使其看起来不应该“硬编码”,我想知道是否有简单的方法添加标题“Dog”和所有数组值,添加标题“Cat”和所有数组值。
解决方案
无需为狗和猫分别创建 json 对象。这将在编组数据时导致单独的 json 对象。
您尝试的方法基本上是适当且无用的。
方法应该创建一个结果结构,它将狗和猫结构作为字段,类型分别作为它们的切片。举个例子:
package main
import (
"fmt"
"encoding/json"
"log"
)
type Result struct{
Dog []Dog
Cat []Cat
}
type Dog struct{
Breed string
Color string
}
type Cat struct {
Breed string
Color string
}
func main(){
dogs := []Dog{
{"Chihuahua", "brown"},
{"Pug", "white"},
}
cats := []Cat{
{"British", "white"},
{"Ragdoll", "gray"},
}
result := Result{
Dog: dogs,
Cat: cats,
}
output, err := json.MarshalIndent(result, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
}
输出:
{
"Dog": [
{
"Breed": "Chihuahua",
"Color": "brown"
},
{
"Breed": "Pug",
"Color": "white"
}
],
"Cat": [
{
"Breed": "British",
"Color": "white"
},
{
"Breed": "Ragdoll",
"Color": "gray"
}
]
}
Go 操场上的工作代码
推荐阅读
- ios - 线程 1:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)与 Firebase
- mysql - MySQL中有没有一种方法可以对子字符串使用类似“IN”的函数
- javascript - 如何使用 LAST_INSERT_ID() 插入具有相同值的多条记录
- java - 如何在 JNA 中使用 kotlin-native lib
- python-2.7 - Python 错误:文件...球形.py...导入 f_utils...ImportError:DLL 加载失败:找不到指定的模块
- c++ - 将整数乘以适当分数的快速方法,无需浮点数或溢出
- reactjs - 谷歌应用程序脚本不会选择电子表格中的特定工作表
- python - 如何获取计划的芹菜任务的任务对象?
- swift - 无法以编程方式将字典数组中的行添加到 NSTable
- r - 使用 react-ace 突出显示 R 语言语法