Skip to content

Instantly share code, notes, and snippets.

@Anil8753
Last active December 22, 2021 14:37
Show Gist options
  • Save Anil8753/aefc9949b42831fb2e10b69b47360785 to your computer and use it in GitHub Desktop.
Save Anil8753/aefc9949b42831fb2e10b69b47360785 to your computer and use it in GitHub Desktop.

Revisions

  1. Anil8753 revised this gist Dec 22, 2021. 1 changed file with 3 additions and 4 deletions.
    7 changes: 3 additions & 4 deletions struct-json-sort.go
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,4 @@
    // You can edit this code!
    // Click here and start typing.

    package main

    import (
    @@ -40,9 +39,9 @@ func main() {
    fmt.Println(err)
    }

    fmt.Println(string(dataBytes))
    fmt.Println("Original -> ", string(dataBytes))

    n, _ := JsonRemarshal(dataBytes)
    fmt.Println(string(n))
    fmt.Println("Sorted Keys -> ", string(n))

    }
  2. Anil8753 created this gist Dec 22, 2021.
    48 changes: 48 additions & 0 deletions struct-json-sort.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    // You can edit this code!
    // Click here and start typing.
    package main

    import (
    "encoding/json"
    "fmt"
    )

    type AmountType struct {
    Value string `json:"value"`
    Name string `json:"name"`
    }

    type Data struct {
    Source string `json:"source"`
    Target string `json:"target"`
    Amount AmountType `json:"amount"`
    }

    func JsonRemarshal(bytes []byte) ([]byte, error) {
    var ifce interface{}
    err := json.Unmarshal(bytes, &ifce)
    if err != nil {
    return []byte{}, err
    }
    output, err := json.Marshal(ifce)
    if err != nil {
    return []byte{}, err
    }
    return output, nil
    }

    func main() {
    at := AmountType{Value: "100", Name: "$"}
    data := Data{Source: "Alice", Target: "Bob", Amount: at}

    dataBytes, err := json.Marshal(data)
    if err != nil {
    fmt.Println(err)
    }

    fmt.Println(string(dataBytes))

    n, _ := JsonRemarshal(dataBytes)
    fmt.Println(string(n))

    }