使用特定顺序序列化地图 [英] Serialize a map using a specific order

查看:154
本文介绍了使用特定顺序序列化地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用字符串作为键和值的映射。我有一个指定映射值顺序的键数组。



我想将该映射序列化为JSON,但保持在数组上定义的顺序。



这里有一个示例代码: http:



pre> {
name:John,
age:20
}

但是,如果我直接序列化地图,键是按字母顺序排列的:

  {
age:20,
name:John
}

我可以将它序列化为一个映射数组,从而保持顺序,但是会产生大量不受欢迎的字符:

  [
{
name:John
},
{
age: 20
}
]

在我的真实代码中,我需要序列化广告结果在文本文件中指定的数据库查询,我需要维护列顺序。我不能使用结构体,因为在编译时不知道列。



编辑:稍后我不需要阅读JSON指定的顺序。生成的JSON旨在被人们阅读,所以我只是希望它尽可能以人性化的方式可读。



我可以使用自定义格式,但JSON非常适合我为此。



谢谢!

解决方案

真的不需要使用 json.Marshal ,你可以简单地实现你自己的函数,如这个

 类型OrderedMap map [string] string 

func(om OrderedMap)ToJson(order ... string)string {
buf:=&; bytes.Buffer {}
buf.Write([] byte {'{',' \\\
'})
l:= len(order)
for i,k:=范围顺序{
fmt.Fprintf(buf,\ t\%s\ :\%v \,k,om [k])
if i < l-1 {
buf.WriteByte(',')
}
buf.WriteByte('\\\
')
}
buf.Write([] (){
om:= OrderedMap {
age:20,
name:John,
}
fmt.Println(om.ToJson(name,age))
}


I have a map that uses string for both key and value. I have an array of keys that specifies the order of the values of the map.

I want to serialize that map to a JSON, but keeping the order defined on the array.

There is a sample code here: http://play.golang.org/p/A52GTDY6Wx

I want to serialize it as:

{
  "name": "John",
  "age": "20"
}

But if I serialize the map directly, the keys are ordered alphabetically:

{      
  "age": "20",
  "name": "John"
}

I can serialize it as an array of maps, thus keeping the order, however that generates a lot of undesired characters:

[
  {
    "name": "John"
  },
  {
    "age": "20"
  }
]

In my real code I need to serialize the results of a database query which is specified in a text file, and I need to maintain the column order. I cannot use structs because the columns are not known at compile time.

EDIT: I don't need to read the JSON later in the specified order. The generated JSON is meant to be read by people, so I just want it to be as humanly readable as possible.

I could use a custom format but JSON suits me perfectly for this.

Thanks!

解决方案

For that specific requirement you really don't need to use json.Marshal at all, you can simply implement your own function like this:

type OrderedMap map[string]string

func (om OrderedMap) ToJson(order ...string) string {
    buf := &bytes.Buffer{}
    buf.Write([]byte{'{', '\n'})
    l := len(order)
    for i, k := range order {
        fmt.Fprintf(buf, "\t\"%s\": \"%v\"", k, om[k])
        if i < l-1 {
            buf.WriteByte(',')
        }
        buf.WriteByte('\n')
    }
    buf.Write([]byte{'}', '\n'})
    return buf.String()
}
func main() {
    om := OrderedMap{
        "age":  "20",
        "name": "John",
    }
    fmt.Println(om.ToJson("name", "age"))
}

这篇关于使用特定顺序序列化地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆