I am using the Dart library json_path to filter JSON objects. When I try to filter objects based on a field value, the filter works if the object values are stored inside an array, while it does not if it is a regular field of the parent object, see the example. I tried several syntax variations. All work on the array but not on the single object, what am I missing?
import 'dart:convert';
import 'package:json_path/json_path.dart';
void main() {
// This example works, note the inner array with just one element
final docArray = jsonDecode('''
{
"store": {
"auto":
[
{
"price": 10
}
]
}
} ''');
// This example does not work, single field instead of array
final docObject = jsonDecode('''
{
"store": {
"auto":
{
"price": 10
}
}
} ''');
print('\nauto Object :');
JsonPath(r'$.store.auto[?@.price < 20]').readValues(docObject).forEach(print);
print('auto Array:');
JsonPath(r'$.store.auto[?@.price < 20]').readValues(docArray).forEach(print);
}
Output:
auto object :
auto Array: {price: 10}
Process finished with exit code 0
With the $.store.auto
in your expression, you already point to one property in store
(auto
). So that's a single node, meaning that there is no array to filter on (and a filter expression always returns an array).
If you want to get a list of the properties that have a price < 20, you can do:
JsonPath(r'$.store[?@.price < 20]')
It's a bit easier to see in this screenshot:
I added a second property in the store
object, and added a name
attribute to them to make it easier to see what nodes are being selected.
My test bed on Zapp.run: https://zapp.run/edit/jsonpath-testing-zs9u06qxs9v0