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 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名