douweibeng5219 2019-07-24 08:40
浏览 174
已采纳

Go中的json序列化后的匿名结构

I want achieve such format for output json

{
    "2019-07-22": {
        "something": {
            "type": "ENTRY",
            "id": 1766617,
        },
        "something2": {
            "type": "ENTRY",
            "id": 1766617,
        },
    },
    "2019-07-23": {
        "something": {
            "type": "ENTRY",
            "id": 1766618,
        },
        "something2": {
            "type": "ENTRY",
            "id": 1766620,
        },
    },
}

So far I've split those data into 3 structs:

type Response struct {
    Days map[string]Day
}

type Day struct {
    Entries map[string]Entry
}

type Entry struct {
    type            string `json:"type"`
    Id              int    `json:"id"`
}

After serialize into json I have structure with field names and nested json objects which is wrong:

{
    "Days": {
        "2019-07-22": {
            "Entries": {
                "something": {
                    "type": "ENTRY",
                    "id": 1766617
                },
                "something2": {
                    "type": "ENTRY",
                    "id": 1766617
                }
            }
        }
    }
}

Is there possibility to skip those field names in Response:Days and Day:Entries fields? I will not deserialize json into structs so only problem is serialization. I can't change json structure because of BC breakes.

  • 写回答

1条回答 默认 最新

  • duanhu2414 2019-07-24 11:29
    关注

    To achieve the json you want your Response type should be a map of maps.

    type Response map[string]map[string]Entry
    
    type Entry struct {
        Type string `json:"type"`
        Id   int    `json:"id"`
    }
    

    https://play.golang.com/p/4GBEZi_TS9m

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

报告相同问题?

悬赏问题

  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题