Skip to content

ranjith19/jsonhasher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Consistent JSON Hasher in go

This module generates consistent json sha256 hashes irrespective of key orders.

Use cases:

  1. Compare two different JSONs for equality
  2. Generate keys based on JSON values in key value stores. (for example caching API response combination of inputs.)

Example Usage

package main

import (
    "fmt"
    "github.com/ranjith19/jsonhasher"
)

func main() {
    input1 := `{"a": 1, "c": {"x": true, "y": false}, "b": 2}`
    input2 := `{"b": 2, 
    "a": 1, "c": {"x": true, "y": false}}`

    h1, _ := jsonhasher.HashJsonString(input1)
    h2, _ := jsonhasher.HashJsonString(input2)

    fmt.Println(*h1)
    fmt.Println(*h2)
}

Will output

e8a8a051f649f3313bf6a02d3d117783ea53da1c6a7e7611b9d2a224496ed80b
e8a8a051f649f3313bf6a02d3d117783ea53da1c6a7e7611b9d2a224496ed80b

Irrespective of formatting on the JSON or the order of the keys, the hash will be consistent.

Try this at go playground. Another example here

Longer/Shorter hashes

You can use HashJsonStringSha1 or HashJsonStringSha512 methods.

Hashing structs

You can use HashInterface method to hash using exported fields of the struct. Example here

testing

Run tests by

go test

Run coverage

go test -covermode=count -coverprofile=coverage.out; go tool cover -html=coverage.out;

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages