Flattening marshalled JSON structs with anonymous members in Go

前端 未结 7 1980
感情败类
感情败类 2021-01-02 10:20

Given the following code: (reproduced here at play.golang.org.)

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 11:09

    This is kinda tricky. One thing for certain, however, is that the doc addresses your sample with this:

    Interface values encode as the value contained in the interface

    from the same link so there is nothing more to do. "Anything" while it is anonymous it is an interface variable and so I might expect the behavior in your sample.

    I took your code and made some changes. This example works but has some side effects. In this case I needed to change the ID member names so that there was nome collision. But then I also changed the json tag. If I did not change the tag then the code seemed to take too long to run and the overlapping tags were both omitted. (here).

    PS: I cannot say with any certainty but I would guess that there is a problem with the assumption. I would assume that anything that I was going to Marshal I would want to be able to UnMarshal. Your flattener just won't do that. If you want a flattener you might have to fork the JSON encoder and add some values to the tags (much like there is a 'omitempty' you might add a 'flatten'.

提交回复
热议问题