jsoniter_any_object_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package jsoniter
  2. import (
  3. "testing"
  4. "github.com/json-iterator/go/require"
  5. )
  6. func Test_read_object_as_any(t *testing.T) {
  7. should := require.New(t)
  8. any := Get([]byte(`{"a":"b","c":"d"}`))
  9. should.Equal(`{"a":"b","c":"d"}`, any.ToString())
  10. // partial parse
  11. should.Equal("b", any.Get("a").ToString())
  12. should.Equal("d", any.Get("c").ToString())
  13. should.Equal(2, len(any.Keys()))
  14. any = Get([]byte(`{"a":"b","c":"d"}`))
  15. // full parse
  16. should.Equal(2, len(any.Keys()))
  17. should.Equal(2, any.Size())
  18. should.True(any.ToBool())
  19. should.Equal(1, any.ToInt())
  20. should.Equal(Object, any.ValueType())
  21. should.Nil(any.LastError())
  22. should.Equal("b", any.GetObject()["a"].ToString())
  23. }
  24. func Test_object_lazy_any_get(t *testing.T) {
  25. should := require.New(t)
  26. any := Get([]byte(`{"a":{"b":{"c":"d"}}}`))
  27. should.Equal("d", any.Get("a", "b", "c").ToString())
  28. }
  29. func Test_object_lazy_any_get_all(t *testing.T) {
  30. should := require.New(t)
  31. any := Get([]byte(`{"a":[0],"b":[1]}`))
  32. should.Contains(any.Get('*', 0).ToString(), `"a":0`)
  33. }
  34. func Test_object_lazy_any_get_invalid(t *testing.T) {
  35. should := require.New(t)
  36. any := Get([]byte(`{}`))
  37. should.Equal(Invalid, any.Get("a", "b", "c").ValueType())
  38. should.Equal(Invalid, any.Get(1).ValueType())
  39. }
  40. func Test_wrap_object(t *testing.T) {
  41. should := require.New(t)
  42. type TestObject struct {
  43. Field1 string
  44. field2 string
  45. }
  46. any := Wrap(TestObject{"hello", "world"})
  47. should.Equal("hello", any.Get("Field1").ToString())
  48. any = Wrap(TestObject{"hello", "world"})
  49. should.Equal(2, any.Size())
  50. }
  51. func Test_any_within_struct(t *testing.T) {
  52. should := require.New(t)
  53. type TestObject struct {
  54. Field1 Any
  55. Field2 Any
  56. }
  57. obj := TestObject{}
  58. err := UnmarshalFromString(`{"Field1": "hello", "Field2": [1,2,3]}`, &obj)
  59. should.Nil(err)
  60. should.Equal("hello", obj.Field1.ToString())
  61. should.Equal("[1,2,3]", obj.Field2.ToString())
  62. }