Golang。将Map转换为JSON,但保留键的顺序。

huangapple go评论89阅读模式
英文:

Golang. Map to JSON, but preserve the key order

问题

我有一个地图对象,当使用json.Marshal(myMapObjct)对其进行序列化时,Golang会按字母顺序对键进行排序,这导致数据处理时出现问题。在创建JSON结构后,保留键的顺序非常重要。是否有可能以这种方式进行序列化,还是我需要为这种特定情况编写自己的序列化器?

以下是负责生成JSON结构的代码片段:

// serializedTraffic将map包装在naturalTraffic中,并将其序列化为字符串。
func serializedTraffic(payload string) (string, error) {
    trafficMap := naturalTraffic(string(payload))
    traffic, err := json.Marshal(trafficMap)
    return string(traffic), err
}

// naturalTraffic将'payload'混淆为类似JSON的结构。
func naturalTraffic(payload string) map[string]string {
    // 决定JSON结构中将有多少个键。
    indexChar := 0
    maxChars := 126
    minChars := 16

    var jsonObject = make(map[string]string)

    // 构建JSON结构。
    for indexChar < len(payload) {
        rand.Seed(time.Now().UnixNano())
        chunkSize := rand.Intn(maxChars-minChars) + minChars
        if len(payload) < indexChar+chunkSize {
            chunkSize = len(payload) - indexChar
        }
        key := randomPopularWord()
        jsonObject[key] = base64.StdEncoding.EncodeToString([]byte(payload[indexChar : indexChar+chunkSize]))
        indexChar += chunkSize
    }

    return jsonObject
}

请注意,我只翻译了你提供的代码部分。

英文:

I've a map object and when it's serialized using json.Marshal(myMapObjct) the Golang sorts the keys in alphabetic order, which is causing issues on how the data is being processed. It's important to preserve the key ordering once the JSON structure has been created into a slice of bytes. Is it possible to serialize it in such a way or do I need to write my own serializer for this specific edge case?

This is the code snippet responsible for generating the JSON structure:

// serializedTraffic wraps around naturalTraffic and serializes map to string.
func serializedTraffic(payload string) (string, error) {
    trafficMap := naturalTraffic(string(payload))
    traffic, err := json.Marshal(trafficMap)
    return string(traffic), err
}

    // naturalTraffic obfuscates &#39;payload&#39; into JSON-like structure.
func naturalTraffic(payload string) map[string]string {
    // Decide on how many keys there will be in the JSON structure.
    indexChar := 0
    maxChars := 126
    minChars := 16

    var jsonObject = make(map[string]string)

    // Build the JSON structure.
    for indexChar &lt; len(payload) {
	    rand.Seed(time.Now().UnixNano())
	    chunkSize := rand.Intn(maxChars-minChars) + minChars
	    if len(payload) &lt; indexChar+chunkSize {
		    chunkSize = len(payload) - indexChar
	    }
	    key := randomPopularWord()
	    jsonObject[key] = base64.StdEncoding.EncodeToString([]byte(payload[indexChar : indexChar+chunkSize]))
 	    indexChar += chunkSize
    }

    return jsonObject
}

答案1

得分: 1

根据建议,我提供了一个修复代码的不同结构。

type elem struct{ key, val string }

type object []elem

func (o object) MarshalJSON() (out []byte, err error) {
	if o == nil {
		return []byte(`null`), nil
	}
	if len(o) == 0 {
		return []byte(`{}`), nil
	}

	out = append(out, '{')
	for _, e := range o {
		key, err := json.Marshal(e.key)
		if err != nil {
			return nil, err
		}
		val, err := json.Marshal(e.val)
		if err != nil {
			return nil, err
		}
		out = append(out, key...)
		out = append(out, ':')
		out = append(out, val...)
		out = append(out, ',')
	}
	// replace last ',' with '}'
	out[len(out)-1] = '}'
	return out, nil
}

// serializedTraffic wraps around naturalTraffic and serializes map to string.
func serializedTraffic(payload string) (string, error) {
	trafficMap := naturalTraffic(string(payload))
	traffic, err := trafficMap.MarshalJSON()
	return string(traffic), err
}

// naturalTraffic obfuscates 'payload' into JSON-like structure.
func naturalTraffic(payload string) object {
	// Decide on how many keys there will be in the JSON structure.
	indexChar := 0
	maxChars := 126
	minChars := 16

	var jsonObject object

	// Build the JSON structure.
	for indexChar < len(payload) {
		rand.Seed(time.Now().UnixNano())
		chunkSize := rand.Intn(maxChars-minChars) + minChars
		if len(payload) < indexChar+chunkSize {
			chunkSize = len(payload) - indexChar
		}
		key := randomPopularWord()
		jsonObject = append(jsonObject, elem{
			key: key,
			val: base64.StdEncoding.EncodeToString([]byte(payload[indexChar : indexChar+chunkSize])),
		})
		indexChar += chunkSize
	}

	return jsonObject
}

以上是修复后的代码结构。

英文:

As per suggestions I'm providing a different structure which fixes the code.

	type elem struct{ key, val string }
type object []elem
func (o object) MarshalJSON() (out []byte, err error) {
if o == nil {
return []byte(`null`), nil
}
if len(o) == 0 {
return []byte(`{}`), nil
}
out = append(out, &#39;{&#39;)
for _, e := range o {
key, err := json.Marshal(e.key)
if err != nil {
return nil, err
}
val, err := json.Marshal(e.val)
if err != nil {
return nil, err
}
out = append(out, key...)
out = append(out, &#39;:&#39;)
out = append(out, val...)
out = append(out, &#39;,&#39;)
}
// replace last &#39;,&#39; with &#39;}&#39;
out[len(out)-1] = &#39;}&#39;
return out, nil
}
// serializedTraffic wraps around naturalTraffic and serializes map to string.
func serializedTraffic(payload string) (string, error) {
trafficMap := naturalTraffic(string(payload))
traffic, err := trafficMap.MarshalJSON()
return string(traffic), err
}
// naturalTraffic obfuscates &#39;payload&#39; into JSON-like structure.
func naturalTraffic(payload string) object {
// Decide on how many keys there will be in the JSON structure.
indexChar := 0
maxChars := 126
minChars := 16
var jsonObject object
// Build the JSON structure.
for indexChar &lt; len(payload) {
rand.Seed(time.Now().UnixNano())
chunkSize := rand.Intn(maxChars-minChars) + minChars
if len(payload) &lt; indexChar+chunkSize {
chunkSize = len(payload) - indexChar
}
key := randomPopularWord()
jsonObject = append(jsonObject, elem{
key: key,
val: base64.StdEncoding.EncodeToString([]byte(payload[indexChar : indexChar+chunkSize])),
})
indexChar += chunkSize
}
return jsonObject
}

huangapple
  • 本文由 发表于 2022年1月9日 01:21:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/70634715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定