Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use tick for json string; add test examples #1

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Go MapSlice for ordered marshal/ unmarshal of maps in JSON

# Example

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

```go
package main

Expand Down
30 changes: 0 additions & 30 deletions _example/example.go

This file was deleted.

61 changes: 61 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package mapslice_test

import (
"encoding/json"
"fmt"
"log"

"github.com/ake-persson/mapslice-json"
)

func main() {
ms := mapslice.MapSlice{
mapslice.MapItem{Key: "abc", Value: 123},
mapslice.MapItem{Key: "def", Value: 456},
mapslice.MapItem{Key: "ghi", Value: 789},
}

b, err := json.Marshal(ms)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))

ms = mapslice.MapSlice{}
if err := json.Unmarshal(b, &ms); err != nil {
log.Fatal(err)
}

fmt.Println(ms)
}

func ExampleMapSlice_MarshalJSON() {
ms := mapslice.MapSlice{
mapslice.MapItem{Key: "abc", Value: 123},
mapslice.MapItem{Key: "def", Value: 456},
mapslice.MapItem{Key: "ghi", Value: 789},
}

b, err := json.Marshal(ms)
if err != nil {
panic(err)
}

fmt.Printf("%s", b)

// Output:
// {"abc":123,"def":456,"ghi":789}
}

func ExampleMapSlice_UnmarshalJSON() {
var ms = mapslice.MapSlice{}

if err := json.Unmarshal([]byte(`{"abc":123,"def":456,"ghi":789}`), &ms); err != nil {
panic(err)
}

fmt.Printf("%s", ms)

// Output:
// [{abc 123} {def 456} {ghi 789}]
}
4 changes: 2 additions & 2 deletions mapslice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestMarshal(t *testing.T) {
t.Fatal(err)
}

e := "{\"abc\":123,\"def\":456,\"ghi\":789}"
e := `{"abc":123,"def":456,"ghi":789}`
zamicol marked this conversation as resolved.
Show resolved Hide resolved
r := string(b)

if r != e {
Expand All @@ -39,7 +39,7 @@ func TestMarshalError(t *testing.T) {

func TestUnmarshal(t *testing.T) {
ms := MapSlice{}
if err := json.Unmarshal([]byte("{\"abc\":123,\"def\":456,\"ghi\":789}"), &ms); err != nil {
if err := json.Unmarshal([]byte(`{"abc":123,"def":456,"ghi":789}`), &ms); err != nil {
t.Fatal(err)
}

Expand Down