jsoniter_any_object_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package jsoniter
  2. import (
  3. "github.com/json-iterator/go/require"
  4. "testing"
  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. obj := struct {
  24. A string
  25. }{}
  26. any.ToVal(&obj)
  27. should.Equal("b", obj.A)
  28. }
  29. func Test_object_lazy_any_get(t *testing.T) {
  30. should := require.New(t)
  31. any := Get([]byte(`{"a":{"b":{"c":"d"}}}`))
  32. should.Equal("d", any.Get("a", "b", "c").ToString())
  33. }
  34. func Test_object_lazy_any_get_all(t *testing.T) {
  35. should := require.New(t)
  36. any := Get([]byte(`{"a":[0],"b":[1]}`))
  37. should.Contains(any.Get('*', 0).ToString(), `"a":0`)
  38. }
  39. func Test_object_lazy_any_get_invalid(t *testing.T) {
  40. should := require.New(t)
  41. any := Get([]byte(`{}`))
  42. should.Equal(Invalid, any.Get("a", "b", "c").ValueType())
  43. should.Equal(Invalid, any.Get(1).ValueType())
  44. }
  45. func Test_wrap_object(t *testing.T) {
  46. should := require.New(t)
  47. type TestObject struct {
  48. Field1 string
  49. field2 string
  50. }
  51. any := Wrap(TestObject{"hello", "world"})
  52. should.Equal("hello", any.Get("Field1").ToString())
  53. any = Wrap(TestObject{"hello", "world"})
  54. should.Equal(2, any.Size())
  55. should.Equal(`{"Field1":"hello"}`, any.Get('*').ToString())
  56. }
  57. func Test_any_within_struct(t *testing.T) {
  58. should := require.New(t)
  59. type TestObject struct {
  60. Field1 Any
  61. Field2 Any
  62. }
  63. obj := TestObject{}
  64. err := UnmarshalFromString(`{"Field1": "hello", "Field2": [1,2,3]}`, &obj)
  65. should.Nil(err)
  66. should.Equal("hello", obj.Field1.ToString())
  67. should.Equal("[1,2,3]", obj.Field2.ToString())
  68. }