Skip to content

Commit 1c9ac69

Browse files
author
Thomas Hurst
committed
Improve JSONPointer/Path output
Display multiple results as a single JSON array rather than individual items which are likely to be more difficult to consume.
1 parent 4fb72a6 commit 1c9ac69

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

src/main.rs

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use clap::Parser;
55
use color_eyre::Result;
66
use colored_json::to_colored_json_auto;
77
use html2text::render::text_renderer::RichAnnotation;
8+
use serde_json::Value;
89
use serde_json_path::JsonPath;
910
use serpapi::Client;
1011

@@ -129,18 +130,26 @@ fn default_colour_map(annotation: &RichAnnotation) -> (String, String) {
129130
}
130131
}
131132

132-
fn render_json(args: &Cli, json: &serde_json::Value) -> Result<(), Box<dyn std::error::Error>> {
133+
fn render_json(args: &Cli, json: &Value) -> Result<(), Box<dyn std::error::Error>> {
133134
if let Some(path) = &args.jsonpath {
134-
for node in path.query(&json) {
135-
println!("{}", to_colored_json_auto(&node)?);
136-
}
135+
let filtered = Value::Array(path.query(&json).into_iter().cloned().collect());
136+
println!("{}", to_colored_json_auto(&filtered)?);
137137
} else if !args.jsonpointer.is_empty() {
138-
for pointer in &args.jsonpointer {
139-
if let Some(node) = json.pointer(pointer) {
140-
println!("{}", to_colored_json_auto(&node)?);
141-
} else {
142-
println!("null");
143-
}
138+
if args.jsonpointer.len() > 1 {
139+
// If we have more than one query, return them as an array
140+
let filtered = Value::Array(
141+
args.jsonpointer
142+
.iter()
143+
.map(|p| json.pointer(p).unwrap_or_else(|| &Value::Null))
144+
.cloned()
145+
.collect(),
146+
);
147+
println!("{}", to_colored_json_auto(&filtered)?);
148+
} else {
149+
let node = json
150+
.pointer(&args.jsonpointer[0])
151+
.unwrap_or_else(|| &Value::Null);
152+
println!("{}", to_colored_json_auto(&node)?);
144153
}
145154
} else {
146155
println!("{}", to_colored_json_auto(&json)?);

0 commit comments

Comments
 (0)