This is a Go library that provides an OrderedJSON data structure which preserves the insertion order of keys during JSON marshaling and unmarshaling operations.
This README was generated by AI and may not reflect all nuances of the implementation. Please refer to the source code for the most accurate and up-to-date information.
- Preserves JSON key insertion order during marshaling/unmarshaling
- Simple API with
New(),UnmarshalJSON(),MarshalJSON(), andDelete()methods - No external dependencies beyond Go standard library
- Efficient O(1) value access through internal map structure
go get github.com/lakkiy/orderedjsonpackage main
import (
"encoding/json"
"fmt"
"github.com/lakkiy/orderedjson"
)
func main() {
// Create new OrderedJSON instance
oj := orderedjson.New()
// Unmarshal JSON while preserving key order
jsonData := `{"name": "John", "age": 30, "city": "New York"}`
err := json.Unmarshal([]byte(jsonData), oj)
if err != nil {
panic(err)
}
// Marshal back to JSON with preserved order
result, err := json.Marshal(oj)
if err != nil {
panic(err)
}
fmt.Println(string(result))
// Output: {"name":"John","age":30,"city":"New York"}
// Delete a key
oj.Delete("age")
result, _ = json.Marshal(oj)
fmt.Println(string(result))
// Output: {"name":"John","city":"New York"}
}type OrderedJSON struct {
// Internal fields are unexported
}Creates a new empty OrderedJSON instance.
Implements the json.Unmarshaler interface. Parses JSON data while preserving key insertion order.
Implements the json.Marshaler interface. Serializes the OrderedJSON to JSON format maintaining key order.
Removes the specified key from the OrderedJSON structure while maintaining the order of remaining keys.
- Uses a combination of
[]stringfor key order andmap[string]anyfor value storage - Token-based JSON parsing with
json.NewDecoderto capture insertion order - Key deletion requires both map cleanup and slice manipulation
- Limited functionality compared to full-featured JSON libraries
- Designed for specific use cases - review source code before adoption
- No advanced features like nested object handling, validation, or complex data type support
GNU General Public License v3.0
This project was created for personal use. If you find bugs or need additional features, please review the source code and consider forking the project for your specific needs.