...

Source file src/github.com/stretchr/objx/simple_example_test.go

Documentation: github.com/stretchr/objx

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

View as plain text