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.
CodePudding user response:
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