Skip to content

Respect errors in cb function in ArrayEach and EachKey #53

Description

@lorehov

Suppose we have following code:

    result := []Foo{}
    err := jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
        if err != nil {
            return
        }
        bars, err := extractBars(value)
        if err != nil {
            return
        }
        append(result, Foo{FieldOne: jsonparser.GetString(value, "target"), Bars: bars})
    })

We have no options to stop iterate over data even if our function extractBars will return an error.

I think there are two possible ways of fixing this issue.

1. If we don't care about backward compatibility
Just change cb signature to cb func(value []byte, dataType ValueType, offset int, err error) error.

2. If we respect backward compatibility
Then we could add counterpart for both there functions and name these like IterArray, IterKeys or something like this.

P.S.: In both cases I could contribute with PR.

Activity

  1. buger commented on Jul 12, 2016

    @buger
    Owner

    In our case probably better return true or false.

    This is about easier API vs some speed improvement for some (rare?) cases. Not sure if it will be useful for most of the users.

  2. lorehov commented on Jul 12, 2016

    @lorehov
    Author

    I agree, this is more generic as we could decide to stop iteration even if no error occurs, just because we got enough data.

    Meanwhile I'm using following workaround:

        result := []Foo{}
        var de error = nil
        err := jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
            if err != nil || de != nil {
                return
            }
            bars, err := extractBars(value)
            if err != nil {
                de = err
                return
            }
            append(result, Foo{FieldOne: jsonparser.GetString(value, "target"), Bars: bars})
        })
    

    So given all this do we need IterArray/IterKeys with callback signature cb func(value []byte, dataType ValueType, offset int, err error) bool?

  3. kdar commented on Jul 9, 2017

    @kdar

    Ran into this issue today. I find it weird that it doesn't follow the same style of ObjectEach in this regard.

  4. added a commit that references this issue on Jul 28, 2026
    f6ddf26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions