Skip to content
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

Eval sum() and avg() does not return right answer after filtering array #69

Closed
Joey29-1 opened this issue Jun 14, 2024 · 1 comment · Fixed by #70
Closed

Eval sum() and avg() does not return right answer after filtering array #69

Joey29-1 opened this issue Jun 14, 2024 · 1 comment · Fixed by #70

Comments

@Joey29-1
Copy link

Joey29-1 commented Jun 14, 2024

The sum() and avg() function in Eval() does not return the correct answer if the array of objects is filtered.

	json := []byte(`
	{
		"items": [
			{
				"price":1, 
				"type": "A"
			}, 
			{
				"price":2, 
				"type": "B"
			}, 
			{
				"price":3, 
				"type": "C"
			}
		]
	}`)
	root, err := ajson.Unmarshal(json)
	if err != nil {
		panic(err)
	}
	res1, err := ajson.Eval(root, `sum($.items[?(@.type == "A")].price)`)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Result: %+v", res1.MustNumeric())
	// Expected: 1
	// Actual: panic: wrong type of Node

        res2, err := ajson.Eval(root, `avg($.items[?(@.type == "A")].price)`)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Result: %+v", res2.MustNumeric())
	// Expected: 1
	// Actual: panic: wrong type of Node

I believe the issue is because only one element matches the array filter condition, so it tries to evaluate sum(1), which returns a Null node.

Side question: For eval functions that return a numerical value, what should I expect if none of the elements match the filter condition? 0 or Null node?

@Joey29-1 Joey29-1 changed the title Eval sum() and avg() does not return return answer after filtering array Eval sum() and avg() does not return right answer after filtering array Jun 14, 2024
@spyzhov
Copy link
Owner

spyzhov commented Jun 14, 2024

Fixed.

Side question: For eval functions that return a numerical value, what should I expect if none of the elements match the filter condition? 0 or Null node?

Depends on the request. The Eval function can return Null or Error with the wrong type of Node.
Here, sum and avg will return Null, but if the array of strings is given, then the error wrong type of Node.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants