Skip to content

Commit

Permalink
docs: Add example
Browse files Browse the repository at this point in the history
Add a Scan example for parsing 2D int arrays.
  • Loading branch information
romshark committed Jun 15, 2023
1 parent b954645 commit d336b39
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package jscan_test

import (
"fmt"
"strconv"

"github.com/romshark/jscan/v2"
)
Expand Down Expand Up @@ -196,3 +197,42 @@ func ExampleValidateOne() {
// false
// null
}

func ExampleScan_decode2DIntArray() {
j := `[[1,2,34,567],[8901,2147483647,-1,42]]`

s := [][]int{}
currentIndex := 0
err := jscan.Scan(j, func(i *jscan.Iterator[string]) (err bool) {
switch i.Level() {
case 0: // Root array
return i.ValueType() != jscan.ValueTypeArray
case 1: // Sub-array
if i.ValueType() != jscan.ValueTypeArray {
return true
}
currentIndex = len(s)
s = append(s, []int{})
return false
}
if i.ValueType() != jscan.ValueTypeNumber {
// Unexpected array element type
return true
}
vi, errp := strconv.ParseInt(i.Value(), 10, 32)
if errp != nil {
// Not a valid 32-bit signed integer
return true
}
s[currentIndex] = append(s[currentIndex], int(vi))
return false
})
if err.IsErr() {
fmt.Println(err.Error())
return
}
fmt.Println(s)

// Output:
// [[1 2 34 567] [8901 2147483647 -1 42]]
}

0 comments on commit d336b39

Please sign in to comment.