-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Provide a simple way to access the value of fetch.J #3
Comments
|
Tbh the type assertation is the very similar to the example. j, _ := fetch.Unmarshal[fetch.J](`[1, 2, 3]`)
arr, ok := j.Raw().([]any)
if !ok {
panic("not an array")
} else {
fmt.Println("Array:", arr)
} And if someone needs a specific return type they should use that particular type on the function's generic type. |
I wrote a function to safely convert all types func JConvert[T bool | float64 | string | []any | map[string]any](j J) (T, bool) and compared all the type assertations res, ok := j.Q(".category").Raw()(map[string]any)
res, ok := fetch.JConvert[map[string]any](j.Q(".category"))
res, ok := j.Q(".category").AsObject()
res, ok := j.Q(".tags").Raw()([]any)
res, ok := fetch.JConvert[[]any](j.Q(".tags"))
res, ok := j.Q(".tags").AsArray()
res, ok := j.Q(".price").Raw()(float64)
res, ok := fetch.JConvert[float64](j.Q(".price"))
res, ok := j.Q(".price").AsNumber()
res, ok := j.Q(".name").Raw()(string)
res, ok := fetch.JConvert[string](j.Q(".name"))
res, ok := j.Q(".name").AsString()
res, ok := j.Q(".sold").Raw()(bool)
res, ok := fetch.JConvert[bool](j.Q(".sold"))
res, ok := j.Q(".sold").AsBoolean() I believe the winner is all the |
The package's only way to access the
fetch.J
value is with theRaw()
method, but it's not very useful, because you need to do a type assertion and type switch after it.Method
fetch.J#String()
can be used to access the strings, but it's not intuitive.Perhaps
fetch.J
could have multiple methods that do type assertation.e.g.
But this will not solve the problem of panicking if
j
isnill
The text was updated successfully, but these errors were encountered: