drkbpwk609294 2015-04-01 11:43
浏览 77
已采纳

在Go中的嵌入式结构中组合任意JSON对象

I'm trying to generate JSON objects in the form of {{"s":"v1", "t":"v2"}, {"s":"v3", "t":"v4"}, etc} via embedded structs in Go.

It all works out fine when all Problem items in type Problems []Problem are known ahead of time, as can be seen in func ONE() below and in <kbd>Playground demo</kbd> here.

However, if some K:V pairs contain empty values I'd like to avoid getting {{a},{},{c}} instead of the desired {{a},{c}}, as in func TWO() below and in demo.

Or alternatively, how can I compose probs := Problems{prob0, prob1, prob2, etc} below arbitrarily without knowing ahead of time whether a prob item will be added or omitted?

package main

import (
    "encoding/json"
    "fmt"
)

type Problem struct {
     S string `json:"s,omitempty"`
     T string `json:"t,omitempty"`
}

 type Problems []Problem

 func main() {
     ONE()
     TWO()
}

 func ONE() {
     prob0 := Problem{S: "s0", T: "t0"}
     prob1 := Problem{S: "s1", T: "t1"}
     prob2 := Problem{S: "s2", T: "t2"}

     probs := Problems{prob0, prob1, probe}

       // fmt.Println(probs) // CORRECT: [{s0 t0} {s1 t1} {s2 t2}]

     b, _ := json.Marshal(probs)
     fmt.Println(string(b))

       // CORRECT: [{"s":"s0","t":"t0"},{"s":"s1","t":"t1"},{"s":"s2","t":"t2"}]``
}

 func TWO() {
     prob0 := Problem{S: "s0", T: "t0"}
     prob1 := Problem{S: "", T: ""} // empty values omited BUT NOT {}
     prob2 := Problem{S: "s2", T: "t2"}

     probs := Problems{prob0, prob1, probe}

       // fmt.Println(probs)
       // GOT:    [{s0 t0} { } {s2 t2}]
       // WANTED: [{s0 t0} {s2 t2}]

     b, _ := json.Marshal(probs)
     fmt.Println(string(b))

       // GOT:    [{"s":"s0","t":"t0"},{},{"s":"s2","t":"t2"}]
       // WANTED: [{"s":"s0","t":"t0"},{"s":"s2","t":"t2"}]
}
  • 写回答

3条回答 默认 最新

  • dqh19413 2015-04-01 12:12
    关注

    Once you add an element to the array/slice which you marshal, there's nothing you can do about it. If an element is in the array/slice, it will be marshalled (will be included in the JSON output). How could the json.Marshal() function guess which elements you don't want to marshal? It can't.

    You have to exclude elements which you don't what to appear in the output. In your case you want to exclude empty Problem structs.

    Best/easiest is to create a helper function which creates the []Problem slice for you, empty structs excluded:

    func createProbs(ps ...Problem) []Problem {
        // Remove empty Problem structs:
        empty := Problem{}
        for i := len(ps) - 1; i >= 0; i-- {
            if ps[i] == empty {
                ps = append(ps[:i], ps[i+1:]...)
            }
        }
        return ps
    }
    

    Using this creating a slice is like this:

    probs := createProbs(prob0, prob1, prob2)
    

    Try your modified application on the Go Playground.

    Output of the modified code (notice the empty struct is missing):

    [{"s":"s0","t":"t0"},{"s":"s1","t":"t1"},{"s":"s2","t":"t2"}]
    [{"s":"s0","t":"t0"},{"s":"s2","t":"t2"}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入