Skip to content

Commit d336b39

Browse files
committed
docs: Add example
Add a Scan example for parsing 2D int arrays.
1 parent b954645 commit d336b39

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

example_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package jscan_test
22

33
import (
44
"fmt"
5+
"strconv"
56

67
"github.com/romshark/jscan/v2"
78
)
@@ -196,3 +197,42 @@ func ExampleValidateOne() {
196197
// false
197198
// null
198199
}
200+
201+
func ExampleScan_decode2DIntArray() {
202+
j := `[[1,2,34,567],[8901,2147483647,-1,42]]`
203+
204+
s := [][]int{}
205+
currentIndex := 0
206+
err := jscan.Scan(j, func(i *jscan.Iterator[string]) (err bool) {
207+
switch i.Level() {
208+
case 0: // Root array
209+
return i.ValueType() != jscan.ValueTypeArray
210+
case 1: // Sub-array
211+
if i.ValueType() != jscan.ValueTypeArray {
212+
return true
213+
}
214+
currentIndex = len(s)
215+
s = append(s, []int{})
216+
return false
217+
}
218+
if i.ValueType() != jscan.ValueTypeNumber {
219+
// Unexpected array element type
220+
return true
221+
}
222+
vi, errp := strconv.ParseInt(i.Value(), 10, 32)
223+
if errp != nil {
224+
// Not a valid 32-bit signed integer
225+
return true
226+
}
227+
s[currentIndex] = append(s[currentIndex], int(vi))
228+
return false
229+
})
230+
if err.IsErr() {
231+
fmt.Println(err.Error())
232+
return
233+
}
234+
fmt.Println(s)
235+
236+
// Output:
237+
// [[1 2 34 567] [8901 2147483647 -1 42]]
238+
}

0 commit comments

Comments
 (0)