hiltontj / serde_json_path

Query serde_json Values with JSONPath
https://serdejsonpath.live/
MIT License
50 stars 3 forks source link

Keep track of traversed path and implement `JsonPath::query_path_and_value` #77

Closed FruitieX closed 7 months ago

FruitieX commented 8 months ago

This PR makes it possible to include paths in query results.

A new JsonPath::query_path_and_value function is exposed to avoid breaking backwards compatibility with existing users of JsonPath::query. The return value is a Vec<(Vec<String>, &Value)> where the Vec<String> represents a list of traversed keys and indices to arrive at the serde_json::Value.

For example:

use serde_json::json;
use serde_json_path::JsonPath;

fn main() -> Result<(), serde_json_path::ParseError> {
  let path = JsonPath::parse("$.foo[::2]")?;
  let value = json!({"foo": [1, 2, 3, 4]});
  let result = path.query_path_and_value(&value);
  assert_eq!(result[1].0, vec!["foo", "2"]);
  assert_eq!(result[1].1, 3);
  Ok(())
}

This implementation surely has room for optimization - I was lazy and in a hurry and just passed owned Vec<String> types everywhere.

I am not very familiar with the more advanced features of JSON Paths, but I did verify that the implementation works correctly in basic cases (accessing object members by keys, array indexing, wildcards and such)

FruitieX commented 7 months ago

Closing in favor of #78