在Golang中,当对有序映射进行编组时,可能会出现JSON键排序的问题。

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

Issue with ordering JSON keys when marshalling an ordered map in Golang

问题

我有一个需求,需要迭代给定的 JSON 数据,如果数组只包含一个元素,则将其转换为映射。这个操作很容易实现。

但问题是,我需要将一个 JSON 数据以与原始顺序相同的顺序返回给客户端。

我找到了一些关于使用 OrderedMap 的指南,但对我来说不太一致。

有时候我能得到正确的顺序,有时候不行。

https://go.dev/play/p/b9hmS9BEymy

有人可以给予建议吗?根据日志显示,问题可能出在解析传入的 JSON 数据上。

我非常不愿意使用结构体,因为我需要处理的真实 JSON 数据非常复杂,而且会需要大量的工作,因为有很多变化。

英文:

I have a requirement to iterate a given piece of JSON, and where an array contains a single item to convert that into a map. This is quite easy to do.

The catch is, I need to product a piece of JSON back to the client that is in the same order it was presented.

I have found some guides about using an OrderedMap, but that's inconsistent for me.

Sometimes I get the correct order, sometimes not.

https://go.dev/play/p/b9hmS9BEymy

Can anyone advise? From the logging it appear the issue may be with unmarshalling the incoming JSON

I am really reluctant to use structs, as the real JSON I need to process is very complex, and will need a huuuge amount of work as there are many variations.

答案1

得分: 1

解组 JSON 不会保持顺序,因为你使用了 map[string]interface{}。在 Golang 中,map 是一个哈希表,所以这并不奇怪。你应该创建一个 UnmarshalJSON 函数并进行自定义解组,否则就无法保持顺序。

你可以对除了 map 之外的所有其他类型使用标准解组,这样会更容易。如果你想了解如何做到这一点的详细信息,我也可以解释一下。

英文:

Unmarshalling json will not respect order, as you use map[string]interface{}. Map in golang is a hashmap, so no surprise there. What you should do is create an UnmarshalJSON function as well and do custom unmarshalling, otherwise there is no way to preserve order.

You can use standard unmarshalling for every other type, except map, which should make it a lot easier. If you want details on how to do that, I can explain that too

答案2

得分: 0

如果有人偶然发现这个问题,我通过使用这个包解决了它:

https://gitlab.com/c0b/go-ordered-json

我需要将JSON解组成有序映射,以便映射中的键按照它们的顺序呈现,然后我可以从那里开始处理它们:

var om *OrderedMap = NewOrderedMap()
err := json.Unmarshal([]byte(input), om)
英文:

If anyone ever stumbles across this, I was able to solve it by using this package

https://gitlab.com/c0b/go-ordered-json

I had to Unmarshall the JSON into an orderedmap so the map contained the keys in the order they were presented, and then I was able to work through them from there:

var om *OrderedMap = NewOrderedMap()
err := json.Unmarshal([]byte(input), om)

huangapple
  • 本文由 发表于 2023年2月2日 18:43:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75321965.html
匿名

发表评论

匿名网友

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

确定