doucang9673 2015-08-01 11:54
浏览 52
已采纳

如何将两个json值解组到同一变量中?

I frequently come across json that have same structure but different name. How is it possible to assign all of them in same struct. for example

{
    "e":"g"
    "a":[
        {
            "b":"b1",
            "c":"c1"
        }
        ]
}

and

{
    "e":"f"
    "d":[
        {
            "b":"b1",
            "c":"c1"
        }
        ]
}

have same internal structure but could not be unmarsheled into same golang struct.

  • 写回答

1条回答 默认 最新

  • drob50257447 2015-08-01 18:18
    关注

    Using struct tags for decoding json is intended for the most common use cases. For custom behavior implement the Unmarshaler interface (https://play.golang.org/p/rCpCDvWXGP):

    type InnerStruct struct {
        B, C string
    }
    type OuterStruct struct {
        E string
        A []InnerStruct
    }
    
    func (o *OuterStruct) UnmarshalJSON(bs []byte) error {
        var intermediate map[string]json.RawMessage
        err := json.Unmarshal(bs, &intermediate)
        if err != nil {
            return err
        }
        // e is just e
        e, ok := intermediate["e"]
        if !ok {
            return fmt.Errorf("invalid json, expected `e`")
        }
        err = json.Unmarshal(e, &o.E)
        if err != nil {
            return err
        }
        // a is a or d
        a, ok := intermediate["a"]
        if !ok {
            a, ok = intermediate["d"]
        }
        if !ok {
            return fmt.Errorf("invalid json, expected `a` or `d`")
        }
        err = json.Unmarshal(a, &o.A)
        if err != nil {
            return err
        }
        return nil
    }
    

    In this case I used an intermediate map and delayed the processing of the inner values to match a or d. I'm sure this wasn't the actual data you had to work with, but hopefully it's enough to get you started.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?