simple_example_test.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package objx_test
  2. import (
  3. "testing"
  4. "github.com/stretchr/objx"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/stretchr/testify/require"
  7. )
  8. func TestSimpleExample(t *testing.T) {
  9. // build a map from a JSON object
  10. o := objx.MustFromJSON(`{"name":"Mat","foods":["indian","chinese"], "location":{"county":"hobbiton","city":"the shire"}}`)
  11. // Map can be used as a straight map[string]interface{}
  12. assert.Equal(t, o["name"], "Mat")
  13. // Get an Value object
  14. v := o.Get("name")
  15. require.NotNil(t, v)
  16. // Test the contained value
  17. assert.False(t, v.IsInt())
  18. assert.False(t, v.IsBool())
  19. assert.True(t, v.IsStr())
  20. // Get the contained value
  21. assert.Equal(t, v.Str(), "Mat")
  22. // Get a default value if the contained value is not of the expected type or does not exist
  23. assert.Equal(t, 1, v.Int(1))
  24. // Get a value by using array notation
  25. assert.Equal(t, "indian", o.Get("foods[0]").Data())
  26. // Set a value by using array notation
  27. o.Set("foods[0]", "italian")
  28. assert.Equal(t, "italian", o.Get("foods[0]").Str())
  29. // Get a value by using dot notation
  30. assert.Equal(t, "hobbiton", o.Get("location.county").Str())
  31. }