首页 > 解决方案 > 如何将标头添加到 JSON 以识别数组值的数组名称

问题描述

我正在尝试查看是否有一种方法(简单的方法)可以使用encoding/jsonGO 向 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”和所有数组值。

标签: jsongoencoding

解决方案


无需为狗和猫分别创建 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 操场上的工作代码


推荐阅读