Issues with sorting JSON keys when marshalling ordered maps in Golang

WBOY
Release: 2024-02-09 10:00:28
forward
701 people have browsed it

在 Golang 中编组有序映射时排序 JSON 键的问题

Sorting JSON keys is a common problem when marshalling ordered maps in Golang. When we get data from a database or other data source and marshal it into JSON format, we often need to sort the keys to ensure that the output JSON object has a consistent key order. Implementing this function in Golang is not complicated. We can use a combination of structures and slices to implement the function of sorting keys. We can easily achieve the goal of sorting JSON keys by storing the key-value pairs in a slice of a struct and using the sort package to sort the slices. In this article, we will explain how to sort JSON keys when marshaling an ordered map in Golang, and provide a simple example code to demonstrate the process.

Question content

I need to iterate over a given JSON fragment and the array contains individual items to convert it to a map. This is easy to do.

The problem is, I need to return a piece of JSON to the client in the order it was presented.

I found some guides on using OrderedMap but it doesn't seem consistent to me.

Sometimes I get the correct order, sometimes not.

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

Can anyone suggest? Judging from the logging, the problem may be with unmarshaling the incoming JSON

I'm really reluctant to use structs because the real JSON I need to deal with is very complex and requires a lot of work since there are so many variations.

Workaround

Unmarshaling the json will not follow the order because you use map[string]interface{}. Map in golang is a hashmap, so this is not surprising. What you should do is create an UnmarshalJSON function and do custom unmarshalling, otherwise the order cannot be preserved.

You can use standard unmarshalling for all other types except maps, which should make it easier. If you want details on how to do this I can explain that too

The above is the detailed content of Issues with sorting JSON keys when marshalling ordered maps in Golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!