zeroshade commented on a change in pull request #11359:
URL: https://github.com/apache/arrow/pull/11359#discussion_r741363090



##########
File path: go/arrow/array/binary.go
##########
@@ -117,6 +118,21 @@ func (a *Binary) setData(data *Data) {
        }
 }
 
+func (a *Binary) getOneForMarshal(i int) interface{} {
+       if a.IsNull(i) {
+               return nil
+       }
+       return a.Value(i)
+}
+
+func (a *Binary) MarshalJSON() ([]byte, error) {
+       vals := make([]interface{}, a.Len())
+       for i := 0; i < a.Len(); i++ {
+               vals[i] = a.getOneForMarshal(i)
+       }
+       return json.Marshal(vals)

Review comment:
       From the Go docs on JSON marshalling: 
https://pkg.go.dev/encoding/json#Marshal
   
   > Array and slice values encode as JSON arrays, except that []byte encodes 
as a base64-encoded string, and a nil slice encodes as the null JSON value.
   
   The standard marshalling of byte slices to JSON in go will marshal it to a 
base64-encoded string.

##########
File path: go/arrow/array/decimal128.go
##########
@@ -229,6 +253,67 @@ func (b *Decimal128Builder) newData() (data *Data) {
        return
 }
 
+func (b *Decimal128Builder) unmarshalOne(dec *json.Decoder) error {
+       t, err := dec.Token()
+       if err != nil {
+               return err
+       }
+
+       var out *big.Float
+
+       switch v := t.(type) {
+       case float64:
+               out = big.NewFloat(v)
+       case string:
+               out, _, err = big.ParseFloat(v, 10, 0, big.ToNearestAway)

Review comment:
       No strong rationale, just happened to be what got me the closest to the 
value I had input when I used it and I couldn't think of a good way to easily 
make this configurable in the current interface. I'll add a comment to document 
it.

##########
File path: go/arrow/array/decimal128.go
##########
@@ -229,6 +253,67 @@ func (b *Decimal128Builder) newData() (data *Data) {
        return
 }
 
+func (b *Decimal128Builder) unmarshalOne(dec *json.Decoder) error {
+       t, err := dec.Token()
+       if err != nil {
+               return err
+       }
+
+       var out *big.Float
+
+       switch v := t.(type) {
+       case float64:
+               out = big.NewFloat(v)
+       case string:
+               out, _, err = big.ParseFloat(v, 10, 0, big.ToNearestAway)

Review comment:
       duplicate comment of 
https://github.com/apache/arrow/pull/11359#discussion_r741359958

##########
File path: go/arrow/array/decimal128.go
##########
@@ -229,6 +253,67 @@ func (b *Decimal128Builder) newData() (data *Data) {
        return
 }
 
+func (b *Decimal128Builder) unmarshalOne(dec *json.Decoder) error {
+       t, err := dec.Token()
+       if err != nil {
+               return err
+       }
+
+       var out *big.Float
+
+       switch v := t.(type) {
+       case float64:
+               out = big.NewFloat(v)
+       case string:
+               out, _, err = big.ParseFloat(v, 10, 0, big.ToNearestAway)
+               if err != nil {
+                       return err
+               }
+       case json.Number:

Review comment:
       It's not an alias but an actual type, which would only get used if the 
json encoder sets an option to use it. The `json.Number` type provides helper 
functions for parsing from the string, so the logic wouldn't be the same as 
using string, but instead using the helper functions directly and checking the 
error returns from them

##########
File path: go/arrow/array/fixed_size_list.go
##########
@@ -110,6 +112,44 @@ func (a *FixedSizeList) Release() {
        a.values.Release()
 }
 
+func (a *FixedSizeList) getOneForMarshal(i int) interface{} {
+       if a.IsNull(i) {
+               return nil
+       }
+       slice := a.newListValue(i)
+       defer slice.Release()
+       v, err := json.Marshal(slice)
+       if err != nil {
+               panic(err)
+       }
+
+       return json.RawMessage(v)
+}
+
+func (a *FixedSizeList) MarshalJSON() ([]byte, error) {
+       var buf bytes.Buffer
+       enc := json.NewEncoder(&buf)
+
+       buf.WriteByte('[')

Review comment:
       No, it's just encoding a fixed size list identically to how it encodes 
regular lists, as a nested list. From the perspective of JSON there's no 
difference between a `List` where all of the lists happen to be the same 
length, and a `FixedSizeList`. A fixed size list with `n=3` of Int would encode 
in json as `[ [1,2,3], [4,5,6], [7,8,9] ]`

##########
File path: go/arrow/array/float16_builder.go
##########
@@ -163,3 +168,59 @@ func (b *Float16Builder) newData() (data *Data) {
 
        return
 }
+
+func (b *Float16Builder) unmarshalOne(dec *json.Decoder) error {
+       t, err := dec.Token()
+       if err != nil {
+               return err
+       }
+
+       switch v := t.(type) {
+       case float64:
+               b.Append(float16.New(float32(v)))
+       case string:
+               f, err := strconv.ParseFloat(v, 32)
+               if err != nil {
+                       return err
+               }
+               b.Append(float16.New(float32(f)))

Review comment:
       Currently it will silently truncate

##########
File path: go/arrow/array/interval.go
##########
@@ -279,6 +341,28 @@ func (a *DayTimeInterval) setData(data *Data) {
        }
 }
 
+func (a *DayTimeInterval) getOneForMarshal(i int) interface{} {
+       if a.IsValid(i) {
+               return a.values[i]
+       }
+       return nil
+}
+
+func (a *DayTimeInterval) MarshalJSON() ([]byte, error) {
+       if a.NullN() == 0 {
+               return json.Marshal(a.values)

Review comment:
       Currently DayTime interval would get marshaled as `{ "days": #, 
"milliseconds": # }`, the same would be true for month day nano interval type 
being marshalled as `{ "months": #, "days": #, "nanoseconds": # }`. The only 
one that currently wouldn't get marshalled into a formatted object or string is 
the month interval. The intention I had was that the actual types should be 
defined externally before attempting to parse the JSON as I didn't build any 
arrow type inference into the JSON reader. It requires being passed a schema or 
data type.

##########
File path: go/arrow/array/numeric.gen.go
##########
@@ -80,6 +82,27 @@ func (a *Int64) setData(data *Data) {
        }
 }
 
+func (a *Int64) getOneForMarshal(i int) interface{} {
+       if a.IsNull(i) {
+               return nil
+       }
+
+       return float64(a.values[i]) // prevent uint8 from being seen as binary 
data

Review comment:
       Fair, I'll update the template to only add that to the uint8 type

##########
File path: go/arrow/array/numeric.gen.go
##########
@@ -750,6 +962,22 @@ func (a *Timestamp) setData(data *Data) {
        }
 }
 
+func (a *Timestamp) getOneForMarshal(i int) interface{} {
+       if a.IsNull(i) {
+               return nil
+       }
+       return 
a.values[i].ToTime(a.DataType().(*arrow.TimestampType).Unit).Format("2006-01-02 
15:04:05.999999999")

Review comment:
       using `9` there will leave out trailing zeros from the resulting string 
so this will handle whatever level of precision is provided rather than 
explicitly padding to a specific precision level.

##########
File path: go/arrow/array/numeric.gen.go
##########
@@ -817,6 +1045,22 @@ func (a *Time32) setData(data *Data) {
        }
 }
 
+func (a *Time32) getOneForMarshal(i int) interface{} {
+       if a.IsNull(i) {
+               return nil
+       }
+       return 
a.values[i].ToTime(a.DataType().(*arrow.Time32Type).Unit).Format("15:04:05.999999999")

Review comment:
       using the `9`'s there will drop any trailing zeros so that it will only 
format it to the precision required to represent the value.

##########
File path: go/arrow/array/struct.go
##########
@@ -105,6 +107,36 @@ func (a *Struct) setData(data *Data) {
        }
 }
 
+func (a *Struct) getOneForMarshal(i int) interface{} {
+       if a.IsNull(i) {
+               return nil
+       }
+
+       tmp := make(map[string]interface{})
+       fieldList := a.data.dtype.(*arrow.StructType).Fields()
+       for j, d := range a.fields {
+               tmp[fieldList[j].Name] = d.getOneForMarshal(i)

Review comment:
       currently the Go implementation does not support duplicate field names 
in structs, only in schemas. So at least for now i'm guaranteed that there will 
be no duplicate field names until i make a change to support them in the struct 
type in general.

##########
File path: go/arrow/array/struct.go
##########
@@ -105,6 +107,36 @@ func (a *Struct) setData(data *Data) {
        }
 }
 
+func (a *Struct) getOneForMarshal(i int) interface{} {
+       if a.IsNull(i) {
+               return nil
+       }
+
+       tmp := make(map[string]interface{})
+       fieldList := a.data.dtype.(*arrow.StructType).Fields()
+       for j, d := range a.fields {
+               tmp[fieldList[j].Name] = d.getOneForMarshal(i)
+       }
+       return tmp
+}
+
+func (a *Struct) MarshalJSON() ([]byte, error) {
+       var buf bytes.Buffer
+       enc := json.NewEncoder(&buf)
+
+       buf.WriteByte('[')
+       for i := 0; i < a.Len(); i++ {

Review comment:
       In a struct column, each "value" in the list, is an object consisting of 
keys from the struct field names with values for the corresponding index. 
   
   For example, a `struct<a: int, b: float>` column would be marshalled to `[ 
{"a": <a[0]>, "b": <b[0]>}, {"a": <a[1]>, "b": <b[1]> }, .... ]`. Does that 
make more sense?

##########
File path: go/arrow/array/util_test.go
##########
@@ -0,0 +1,406 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package array_test
+
+import (
+       "bytes"
+       "fmt"
+       "io"
+       "reflect"
+       "strings"
+       "testing"
+
+       "github.com/apache/arrow/go/arrow"
+       "github.com/apache/arrow/go/arrow/array"
+       "github.com/apache/arrow/go/arrow/decimal128"
+       "github.com/apache/arrow/go/arrow/internal/arrdata"
+       "github.com/apache/arrow/go/arrow/memory"
+       "github.com/goccy/go-json"
+       "github.com/stretchr/testify/assert"
+)
+
+var typemap = map[arrow.DataType]reflect.Type{
+       arrow.PrimitiveTypes.Int8:   reflect.TypeOf(int8(0)),
+       arrow.PrimitiveTypes.Uint8:  reflect.TypeOf(uint8(0)),
+       arrow.PrimitiveTypes.Int16:  reflect.TypeOf(int16(0)),
+       arrow.PrimitiveTypes.Uint16: reflect.TypeOf(uint16(0)),
+       arrow.PrimitiveTypes.Int32:  reflect.TypeOf(int32(0)),
+       arrow.PrimitiveTypes.Uint32: reflect.TypeOf(uint32(0)),
+       arrow.PrimitiveTypes.Int64:  reflect.TypeOf(int64(0)),
+       arrow.PrimitiveTypes.Uint64: reflect.TypeOf(uint64(0)),
+}
+
+func TestIntegerArrsJSON(t *testing.T) {
+       const N = 10
+       types := []arrow.DataType{
+               arrow.PrimitiveTypes.Int8,
+               arrow.PrimitiveTypes.Uint8,
+               arrow.PrimitiveTypes.Int16,
+               arrow.PrimitiveTypes.Uint16,
+               arrow.PrimitiveTypes.Int32,
+               arrow.PrimitiveTypes.Uint32,
+               arrow.PrimitiveTypes.Int64,
+               arrow.PrimitiveTypes.Uint64,
+       }
+
+       for _, tt := range types {
+               t.Run(fmt.Sprint(tt), func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                       defer mem.AssertSize(t, 0)
+
+                       jsontest := make([]int, N)
+                       vals := reflect.MakeSlice(reflect.SliceOf(typemap[tt]), 
N, N)
+                       for i := 0; i < N; i++ {
+                               
vals.Index(i).Set(reflect.ValueOf(i).Convert(typemap[tt]))
+                               jsontest[i] = i
+                       }
+
+                       data, _ := json.Marshal(jsontest)
+                       arr, _, err := array.FromJSON(mem, tt, 
bytes.NewReader(data))
+                       assert.NoError(t, err)
+                       defer arr.Release()
+
+                       assert.EqualValues(t, N, arr.Len())
+                       assert.Zero(t, arr.NullN())
+
+                       output, err := json.Marshal(arr)
+                       assert.NoError(t, err)
+                       assert.JSONEq(t, string(data), string(output))
+               })
+               t.Run(fmt.Sprint(tt)+" errors", func(t *testing.T) {
+                       _, _, err := array.FromJSON(memory.DefaultAllocator, 
tt, strings.NewReader(""))
+                       assert.Error(t, err)
+
+                       _, _, err = array.FromJSON(memory.DefaultAllocator, tt, 
strings.NewReader("["))
+                       assert.ErrorIs(t, err, io.ErrUnexpectedEOF)
+
+                       _, _, err = array.FromJSON(memory.DefaultAllocator, tt, 
strings.NewReader("0"))
+                       assert.Error(t, err)
+
+                       _, _, err = array.FromJSON(memory.DefaultAllocator, tt, 
strings.NewReader("{}"))
+                       assert.Error(t, err)
+
+                       _, _, err = array.FromJSON(memory.DefaultAllocator, tt, 
strings.NewReader("[[0]]"))
+                       assert.EqualError(t, err, "json: cannot unmarshal [ 
into Go value of type "+tt.Name())
+               })
+       }
+}
+
+func TestStringsJSON(t *testing.T) {
+       tests := []struct {
+               jsonstring string
+               values     []string
+               valids     []bool
+       }{
+               {"[]", []string{}, []bool{}},
+               {`["", "foo"]`, []string{"", "foo"}, nil},
+               {`["", null]`, []string{"", ""}, []bool{true, false}},
+               // NUL character in string
+               {`["", "some\u0000char"]`, []string{"", "some\x00char"}, nil},
+               // utf8 sequence in string
+               {"[\"\xc3\xa9\"]", []string{"\xc3\xa9"}, nil},
+               // bytes < 0x20 can be represented as JSON unicode escapes
+               {`["\u0000\u001f"]`, []string{"\x00\x1f"}, nil},
+       }
+
+       for _, tt := range tests {
+               t.Run("json "+tt.jsonstring, func(t *testing.T) {
+                       bldr := array.NewStringBuilder(memory.DefaultAllocator)
+                       defer bldr.Release()
+
+                       bldr.AppendValues(tt.values, tt.valids)
+                       expected := bldr.NewStringArray()
+                       defer expected.Release()
+
+                       arr, _, err := array.FromJSON(memory.DefaultAllocator, 
arrow.BinaryTypes.String, strings.NewReader(tt.jsonstring))
+                       assert.NoError(t, err)
+                       defer arr.Release()
+
+                       assert.Truef(t, array.ArrayEqual(expected, arr), 
"expected: %s\ngot: %s\n", expected, arr)
+
+                       data, err := json.Marshal(arr)
+                       assert.NoError(t, err)
+                       assert.JSONEq(t, tt.jsonstring, string(data))
+               })
+       }
+
+       t.Run("errors", func(t *testing.T) {
+               _, _, err := array.FromJSON(memory.DefaultAllocator, 
arrow.BinaryTypes.String, strings.NewReader("[0]"))
+               assert.Error(t, err)
+
+               _, _, err = array.FromJSON(memory.DefaultAllocator, 
arrow.BinaryTypes.String, strings.NewReader("[[]]"))
+               assert.Error(t, err)
+       })
+}
+
+func TestStructArrayFromJSON(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+       defer mem.AssertSize(t, 0)
+
+       jsonStr := `[{"hello": 3.5, "world": true, "yo": "foo"},{"hello": 3.25, 
"world": false, "yo": "bar"}]`
+
+       arr, _, err := array.FromJSON(mem, arrow.StructOf(
+               arrow.Field{Name: "hello", Type: arrow.PrimitiveTypes.Float64},
+               arrow.Field{Name: "world", Type: arrow.FixedWidthTypes.Boolean},
+               arrow.Field{Name: "yo", Type: arrow.BinaryTypes.String},
+       ), strings.NewReader(jsonStr))
+       assert.NoError(t, err)
+       defer arr.Release()
+
+       output, err := json.Marshal(arr)
+       assert.NoError(t, err)
+       assert.JSONEq(t, jsonStr, string(output))
+}
+
+func TestArrayFromJSONMulti(t *testing.T) {
+       arr, _, err := array.FromJSON(memory.DefaultAllocator, arrow.StructOf(
+               arrow.Field{Name: "hello", Type: arrow.PrimitiveTypes.Float64},
+               arrow.Field{Name: "world", Type: arrow.FixedWidthTypes.Boolean},
+               arrow.Field{Name: "yo", Type: arrow.BinaryTypes.String},
+       ), strings.NewReader("{\"hello\": 3.5, \"world\": true, \"yo\": 
\"foo\"}\n{\"hello\": 3.25, \"world\": false, \"yo\": \"bar\"}\n"),
+               array.WithMultipleDocs())
+       assert.NoError(t, err)
+       defer arr.Release()
+
+       assert.EqualValues(t, 2, arr.Len())
+       assert.Zero(t, arr.NullN())
+}
+
+func TestNestedJSONArrs(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+       defer mem.AssertSize(t, 0)
+
+       jsonStr := `[{"hello": 1.5, "world": [1, 2, 3, 4], "yo": [{"foo": 
"2005-05-06", "bar": "15:02:04.123"},{"foo": "1956-01-02", "bar": 
"02:10:00"}]}]`
+
+       arr, _, err := array.FromJSON(mem, arrow.StructOf(
+               arrow.Field{Name: "hello", Type: arrow.PrimitiveTypes.Float64},
+               arrow.Field{Name: "world", Type: 
arrow.ListOf(arrow.PrimitiveTypes.Int32)},
+               arrow.Field{Name: "yo", Type: arrow.FixedSizeListOf(2, 
arrow.StructOf(
+                       arrow.Field{Name: "foo", Type: 
arrow.FixedWidthTypes.Date32},
+                       arrow.Field{Name: "bar", Type: 
arrow.FixedWidthTypes.Time32ms},
+               ))},
+       ), strings.NewReader(jsonStr))
+       defer arr.Release()
+       assert.NoError(t, err)
+
+       v, err := json.Marshal(arr)
+       assert.NoError(t, err)
+       assert.JSONEq(t, jsonStr, string(v))
+}
+
+func TestGetNullsFromJSON(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+       defer mem.AssertSize(t, 0)
+
+       jsonStr := `[
+               {"yo": "thing", "arr": null, "nuf": {"ps": "今日は"}},
+               {"yo": null, "nuf": {"ps": null}, "arr": []},
+               { "nuf": null, "yo": "今日は", "arr": [1,2,3]}
+       ]`
+
+       rec, _, err := array.RecordFromJSON(mem, arrow.NewSchema([]arrow.Field{
+               {Name: "yo", Type: arrow.BinaryTypes.String, Nullable: true},
+               {Name: "arr", Type: arrow.ListOf(arrow.PrimitiveTypes.Int32), 
Nullable: true},
+               {Name: "nuf", Type: arrow.StructOf(arrow.Field{Name: "ps", 
Type: arrow.BinaryTypes.String, Nullable: true}), Nullable: true},
+       }, nil), strings.NewReader(jsonStr))
+       assert.NoError(t, err)
+       defer rec.Release()
+
+       assert.EqualValues(t, 3, rec.NumCols())
+       assert.EqualValues(t, 3, rec.NumRows())
+
+       data, err := json.Marshal(rec)
+       assert.NoError(t, err)
+       assert.JSONEq(t, jsonStr, string(data))
+}
+
+func TestTimestampsJSON(t *testing.T) {
+       tests := []struct {
+               unit    arrow.TimeUnit
+               jsonstr string
+               values  []arrow.Timestamp
+       }{
+               {arrow.Second, `["1970-01-01", "2000-02-29", "3989-07-14", 
"1900-02-28"]`, []arrow.Timestamp{0, 951782400, 63730281600, -2203977600}},
+               {arrow.Nanosecond, `["1970-01-01", "2000-02-29", 
"1900-02-28"]`, []arrow.Timestamp{0, 951782400000000000, -2203977600000000000}},
+       }
+
+       for _, tt := range tests {
+               dtype := &arrow.TimestampType{Unit: tt.unit}
+               bldr := array.NewTimestampBuilder(memory.DefaultAllocator, 
dtype)
+               defer bldr.Release()
+
+               bldr.AppendValues(tt.values, nil)
+               expected := bldr.NewArray()
+               defer expected.Release()
+
+               arr, _, err := array.FromJSON(memory.DefaultAllocator, dtype, 
strings.NewReader(tt.jsonstr))
+               assert.NoError(t, err)
+               defer arr.Release()
+
+               assert.Truef(t, array.ArrayEqual(expected, arr), "expected: 
%s\ngot: %s\n", expected, arr)
+       }
+}
+
+func TestDateJSON(t *testing.T) {
+       t.Run("date32", func(t *testing.T) {
+               bldr := array.NewDate32Builder(memory.DefaultAllocator)
+               defer bldr.Release()
+
+               jsonstr := `["1970-01-06", null, "1970-02-12"]`
+
+               bldr.AppendValues([]arrow.Date32{5, 0, 42}, []bool{true, false, 
true})
+               expected := bldr.NewArray()
+               defer expected.Release()
+
+               arr, _, err := array.FromJSON(memory.DefaultAllocator, 
arrow.FixedWidthTypes.Date32, strings.NewReader(jsonstr))
+               assert.NoError(t, err)
+               defer arr.Release()
+
+               assert.Truef(t, array.ArrayEqual(expected, arr), "expected: 
%s\ngot: %s\n", expected, arr)
+
+               data, err := json.Marshal(arr)
+               assert.NoError(t, err)
+               assert.JSONEq(t, jsonstr, string(data))
+       })
+       t.Run("date64", func(t *testing.T) {
+               bldr := array.NewDate64Builder(memory.DefaultAllocator)
+               defer bldr.Release()
+
+               jsonstr := `["1970-01-02", null, "2286-11-20"]`
+
+               bldr.AppendValues([]arrow.Date64{86400000, 0, 9999936000000}, 
[]bool{true, false, true})
+               expected := bldr.NewArray()
+               defer expected.Release()
+
+               arr, _, err := array.FromJSON(memory.DefaultAllocator, 
arrow.FixedWidthTypes.Date64, strings.NewReader(jsonstr))
+               assert.NoError(t, err)
+               defer arr.Release()
+
+               assert.Truef(t, array.ArrayEqual(expected, arr), "expected: 
%s\ngot: %s\n", expected, arr)
+
+               data, err := json.Marshal(arr)
+               assert.NoError(t, err)
+               assert.JSONEq(t, jsonstr, string(data))
+       })
+}
+
+func TestTimeJSON(t *testing.T) {
+       tententen := 60*(60*(10)+10) + 10
+       tests := []struct {
+               dt       arrow.DataType
+               jsonstr  string
+               valueadd int
+       }{
+               {arrow.FixedWidthTypes.Time32s, `[null, "10:10:10"]`, 123},
+               {arrow.FixedWidthTypes.Time32ms, `[null, "10:10:10.123"]`, 456},

Review comment:
       Right, that's the difference between using 0's or 9's in the format 
string. Using 0's will extend it to the exact precision stated, using 9's will 
truncate trailing zeros.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscr...@arrow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to