spyzhov/ajson

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

Closed this issue · 1 comments

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?

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.