douzhiji2020 2018-10-15 16:59
浏览 318
已采纳

如何将标头添加到JSON以标识数组值的数组名称

I'm trying to look if there's a way (easy way) to add a header to each array in JSON using encoding/json with GO.

What I mean?

Want to have something like this:

{
     "Dog":[
      {
           "breed":"Chihuahua",
           "color":"brown"
      },
      {
           "breed":"Pug",
           "color":"white"
      }
    ],
     "Cat":[
     {
           "breed":"British",
           "color":"white"
     },
           "breed":"Ragdoll",
           "color":"gray"
     }
    ]
}

The main idea is to have a "category" in this case Dog and Cat.

I already have this solution but I'm looking for something that can Improve this.

My code looks like this:

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,
", string(d))
   fmt.Printf("    \"Cat\": %v
}", string(c))

}

The main idea is to have "Dog" and "Cat" as new array but I want to improve my code to don't have it that "hardcoded" to looks as supposed to be, I'm wondering if there's an easy way to add the header "Dog" and all the array values, add the header "Cat" and all the array values.

  • 写回答

1条回答 默认 最新

  • douzhi9478 2018-10-15 17:13
    关注

    There is no need to create json objects separately for dogs and cats. This will lead to separate json objects when marhsalling the data.

    The approach you are trying is basically in appropriate and useless.

    Approach should to create a result struct which will have dogs and cats structs as fields with type as slice of both of them respectively. Take for an example:

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

    Output:

    {
        "Dog": [
            {
                "Breed": "Chihuahua",
                "Color": "brown"
            },
            {
                "Breed": "Pug",
                "Color": "white"
            }
        ],
        "Cat": [
            {
                "Breed": "British",
                "Color": "white"
            },
            {
                "Breed": "Ragdoll",
                "Color": "gray"
            }
        ]
    }
    

    Working Code on Go playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应