Giter Site home page Giter Site logo

kkqy / gokvpairs Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 4 KB

KeyValuePairs is a type that can hold the order of keys of json in Golang. We can use it to preserve the order of keys of json.

License: MIT License

Go 100.00%
golang keyvalue map ordered orderedmap package type

gokvpairs's Introduction

gokvpairs

KeyValuePairs is a type that can hold the order of keys of json object in Golang.

The keys of map in Golang do not guarantee the order, so if we parse json in Golang with map[string]interface{} ,the keys will sorted by alphabet when it is unmarshalled.

This is a problem in some projects, so I defined a type KeyValuePairs[interface{}] to replace map[string]interface{} when I decode those json data whose key order need be preserved.

example

main.go

package main

import (
	"encoding/json"
	"fmt"

	"github.com/kkqy/gokvpairs"
)

type OldTestStruct struct {
	Name          string            `json:"name"`
	OrderedObject map[string]string `json:"ordered_object"`
}
type NewTestStruct struct {
	Name          string                          `json:"name"`
	OrderedObject gokvpairs.KeyValuePairs[string] `json:"ordered_object"`
}

func main() {
	data := []byte(`
	{
		"name": "Test",
		"ordered_object": {
			"c": "value_c",
			"b": "value_b"
		}
	}`)
	fmt.Println("OriginalData:", string(data))
	fmt.Println("====================")

	// Old
	oldTestStruct := OldTestStruct{}
	json.Unmarshal([]byte(data), &oldTestStruct)
	result, _ := json.Marshal(oldTestStruct)
	fmt.Println("Old:", string(result))
	oldTestStruct.OrderedObject["a"] = "value_a"
	result, _ = json.Marshal(oldTestStruct)
	fmt.Println("Old:", string(result))

	fmt.Println("====================")

	// New
	newTestStruct := NewTestStruct{}
	json.Unmarshal([]byte(data), &newTestStruct)
	result, _ = json.Marshal(newTestStruct)
	fmt.Println("New:", string(result))
	newTestStruct.OrderedObject = append(newTestStruct.OrderedObject, gokvpairs.KeyValuePair[string]{Key: "a", Value: "value_a"})
	result, _ = json.Marshal(newTestStruct)
	fmt.Println("New:", string(result))
}

output:

OriginalData: 
        {
                "name": "Test",
                "ordered_object": {
                        "c": "value_c",
                        "b": "value_b"
                }
        }
====================
Old: {"name":"Test","ordered_object":{"b":"value_b","c":"value_c"}}
Old: {"name":"Test","ordered_object":{"a":"value_a","b":"value_b","c":"value_c"}}
====================
New: {"name":"Test","ordered_object":{"c":"value_c","b":"value_b"}}
New: {"name":"Test","ordered_object":{"c":"value_c","b":"value_b","a":"value_a"}}

gokvpairs's People

Contributors

kkqy avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.