json将空索引的切片编组时如何优化空间

时间:2019-05-24 07:06:35

标签: json go marshalling

我有一个指向struct的指针,需要将json编组。用例是大多数索引将为零,而只有少数索引将被填充。在json marshal上,结果是这些nil索引表示为null,占用了大量空间。有没有一种使用标准json或其他库来优化空间的方法?

我也尝试了yaml序列化,但是会产生相同的详细输出。

结构定义

type trieSlice struct {
    Children []*tNode          `json:"c"`
    Charset  map[int32]int8    `json:"l"` // Charset is the legend of what charset is used to create the keys and how to position them in trie array
    logger   loggingapi.Logger `json:"-"`
    capacity int               `json:"-"` // capacity is the slice capacity to have enough to hold all the characters in the charset
}

type tNode struct {
    Children []*tNode `json:"c"`           // children represents the next valid runes AFTER the current one
    IsLeaf   bool     `json:"e,omitempty"` // isLeaf represents if this node represents the end of a valid word
    Value    int16    `json:"v,omitempty"` // value holds the corresponding value for key value pair, where key is the whole tree of nodes starting from parent representing a valid word
}

   func TestSample(t *testing.T) {
        trie := &trieSlice{
          Children: make([]*tNode, 5),
         }

        trie.Children[0] = &tNode{Children: make([]*tNode, 5), IsLeaf: true, Value: 10}
        trie.Children[4] = &tNode{Children: make([]*tNode, 5), IsLeaf: true, Value: 20}


        // YAML marshal
        yamlB, err := yaml.Marshal(trie)
        if err != nil {
          fmt.Println("error in yaml conversion ...", err.Error())
        }
        ioutil.WriteFile("../resources/trieSliceBorder.yml", yamlB, 0644)

        // JSON marshal
        b, err := json.Marshal(trie)
        if err != nil {
           fmt.Println("error while marshalling final trie json ", err.Error())
            t.Fail()
        }
        ioutil.WriteFile("../resources/trieSliceBorder.json", b, 0644)
    }
```

Current serialization output on json.Marshal a *trieSlice:

{
    "c": [null, null, null, null, {
        "c": [null, null, null, null, null, null, null,
            {
                "c": [null, null, null, null, null, null, null],
                "v": 1,
                "e": true
            }
        ]
    }]
}

0 个答案:

没有答案