Skip to main content

graphrt_eval/
path.rs

1//! Dotted JSON paths (`output.items[0].name`) and `{{ var }}` substitution in
2//! assertion values. No JavaScript: a path is identifiers, `.` and `[index]`.
3
4use serde_json::Value as Json;
5
6use crate::error::EvalError;
7
8/// One step of a path.
9#[derive(Clone, Debug, PartialEq, Eq)]
10enum Step {
11    Key(String),
12    Index(usize),
13}
14
15/// A parsed path such as `output.items[0].name` or `outputs["odd key"]`.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct JsonPath {
18    text: String,
19    steps: Vec<Step>,
20}
21
22impl JsonPath {
23    /// Parse a path. An optional `json.` or `$.` prefix is accepted for
24    /// compatibility with Promptfoo `transform` expressions.
25    pub fn parse(text: &str) -> Result<Self, EvalError> {
26        let bad = |why: &str| {
27            EvalError::invalid(format!(
28                "`{text}` is not a supported path ({why}); use identifiers, `.` and `[n]`, e.g. `output.items[0].name` \
29                 (JavaScript transforms are not supported)"
30            ))
31        };
32        let trimmed = text.trim();
33        let body = trimmed.strip_prefix("$.").unwrap_or(trimmed);
34        let mut steps = Vec::new();
35        let mut chars = body.chars().peekable();
36        let mut key = String::new();
37        let flush = |key: &mut String, steps: &mut Vec<Step>| {
38            if !key.is_empty() {
39                steps.push(Step::Key(std::mem::take(key)));
40            }
41        };
42        while let Some(c) = chars.next() {
43            match c {
44                '.' => {
45                    if key.is_empty() && !matches!(steps.last(), Some(Step::Index(_))) {
46                        return Err(bad("empty segment"));
47                    }
48                    flush(&mut key, &mut steps);
49                }
50                '[' => {
51                    flush(&mut key, &mut steps);
52                    let mut inner = String::new();
53                    let mut closed = false;
54                    for c in chars.by_ref() {
55                        if c == ']' {
56                            closed = true;
57                            break;
58                        }
59                        inner.push(c);
60                    }
61                    if !closed {
62                        return Err(bad("unclosed `[`"));
63                    }
64                    let inner = inner.trim();
65                    let quoted = inner
66                        .strip_prefix('"')
67                        .and_then(|s| s.strip_suffix('"'))
68                        .or_else(|| inner.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')));
69                    match (quoted, inner.parse::<usize>()) {
70                        (Some(name), _) => steps.push(Step::Key(name.to_owned())),
71                        (None, Ok(index)) => steps.push(Step::Index(index)),
72                        (None, Err(_)) => return Err(bad("`[...]` needs an index or a quoted key")),
73                    }
74                }
75                c if c.is_alphanumeric() || c == '_' || c == '-' => key.push(c),
76                _ => return Err(bad(&format!("unexpected `{c}`"))),
77            }
78        }
79        if body.ends_with('.') {
80            return Err(bad("trailing `.`"));
81        }
82        flush(&mut key, &mut steps);
83        if steps.is_empty() {
84            return Err(bad("empty path"));
85        }
86        if matches!(steps.first(), Some(Step::Key(k)) if k == "json") && steps.len() > 1 {
87            steps.remove(0);
88        }
89        Ok(Self { text: trimmed.to_owned(), steps })
90    }
91
92    /// The path as written.
93    pub fn as_str(&self) -> &str {
94        &self.text
95    }
96
97    /// Look the path up in `root`. A string holding JSON is parsed on the way,
98    /// so `output.field` works when the output is a JSON text.
99    pub fn get(&self, root: &Json) -> Option<Json> {
100        let mut current = root.clone();
101        for step in &self.steps {
102            if let Json::String(text) = &current
103                && let Ok(parsed) = serde_json::from_str::<Json>(text)
104                && (parsed.is_object() || parsed.is_array())
105            {
106                current = parsed;
107            }
108            current = match (step, current) {
109                (Step::Key(k), Json::Object(mut map)) => map.remove(k)?,
110                (Step::Index(i), Json::Array(items)) => items.into_iter().nth(*i)?,
111                _ => return None,
112            };
113        }
114        Some(current)
115    }
116}
117
118/// Replace `{{ path }}` references in every string of `value`, looking paths up
119/// in `context`. A string that is exactly one reference becomes the referenced
120/// value itself (so `value: "{{expected_docs}}"` can be a list); otherwise the
121/// referenced values are inserted as text. Unknown references are errors.
122pub fn render(value: &Json, context: &Json) -> Result<Json, EvalError> {
123    Ok(match value {
124        Json::String(text) => render_text(text, context)?,
125        Json::Array(items) => Json::Array(items.iter().map(|v| render(v, context)).collect::<Result<_, _>>()?),
126        Json::Object(map) => Json::Object(
127            map.iter().map(|(k, v)| Ok((k.clone(), render(v, context)?))).collect::<Result<_, EvalError>>()?,
128        ),
129        other => other.clone(),
130    })
131}
132
133fn render_text(text: &str, context: &Json) -> Result<Json, EvalError> {
134    if !text.contains("{{") {
135        return Ok(Json::String(text.to_owned()));
136    }
137    let lookup = |expr: &str| -> Result<Json, EvalError> {
138        JsonPath::parse(expr)?.get(context).ok_or_else(|| {
139            EvalError::invalid(format!("`{{{{{}}}}}` does not name a variable of this test", expr.trim()))
140        })
141    };
142    let trimmed = text.trim();
143    if let Some(inner) = trimmed.strip_prefix("{{").and_then(|s| s.strip_suffix("}}"))
144        && !inner.contains("{{")
145        && !inner.contains("}}")
146    {
147        return lookup(inner);
148    }
149    let mut out = String::with_capacity(text.len());
150    let mut rest = text;
151    while let Some(start) = rest.find("{{") {
152        let (before, after) = rest.split_at(start);
153        out.push_str(before);
154        let after = after.get(2..).unwrap_or_default();
155        let Some(end) = after.find("}}") else {
156            return Err(EvalError::invalid(format!("unterminated `{{{{` in `{text}`")));
157        };
158        let value = lookup(after.get(..end).unwrap_or_default())?;
159        match value {
160            Json::String(s) => out.push_str(&s),
161            other => out.push_str(&other.to_string()),
162        }
163        rest = after.get(end + 2..).unwrap_or_default();
164    }
165    out.push_str(rest);
166    Ok(Json::String(out))
167}
168
169#[cfg(test)]
170mod tests {
171    #![allow(clippy::unwrap_used)]
172
173    use super::*;
174    use serde_json::json;
175
176    #[test]
177    fn paths() {
178        let root = json!({"output": {"items": [{"name": "a"}, {"name": "b"}], "odd key": 1}, "text": "{\"n\": 2}"});
179        let get = |p: &str| JsonPath::parse(p).unwrap().get(&root);
180        assert_eq!(get("output.items[1].name"), Some(json!("b")));
181        assert_eq!(get("output[\"odd key\"]"), Some(json!(1)));
182        assert_eq!(get("$.output.items[0]"), Some(json!({"name": "a"})));
183        assert_eq!(get("text.n"), Some(json!(2)), "JSON strings are parsed");
184        assert_eq!(get("output.missing"), None);
185        for bad in ["output.map(x => x)", "a..b", "a[", "a[x]", "", "a."] {
186            assert!(JsonPath::parse(bad).is_err(), "{bad}");
187        }
188    }
189
190    #[test]
191    fn rendering() {
192        let ctx = json!({"name": "Ada", "docs": ["d1", "d2"], "vars": {"n": 3}});
193        assert_eq!(render(&json!("{{docs}}"), &ctx).unwrap(), json!(["d1", "d2"]));
194        assert_eq!(render(&json!("Hello, {{ name }} ({{vars.n}})"), &ctx).unwrap(), json!("Hello, Ada (3)"));
195        assert_eq!(render(&json!({"a": ["{{ name }}"]}), &ctx).unwrap(), json!({"a": ["Ada"]}));
196        assert!(render(&json!("{{ nope }}"), &ctx).is_err());
197        assert!(render(&json!("{{ name"), &ctx).is_err());
198    }
199}