nushell/crates/nu-command/src/commands/from_json.rs

142 lines
4.5 KiB
Rust
Raw Normal View History

2019-05-28 06:00:00 +02:00
use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{Primitive, Signature, TaggedDictBuilder, UntaggedValue, Value};
2019-05-28 06:00:00 +02:00
pub struct FromJson;
impl WholeStreamCommand for FromJson {
fn name(&self) -> &str {
"from json"
}
fn signature(&self) -> Signature {
Signature::build("from json").switch(
"objects",
"treat each line as a separate value",
Some('o'),
)
}
fn usage(&self) -> &str {
"Parse text as .json and create table."
2019-08-27 13:05:51 +02:00
}
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_json(args)
}
}
fn convert_json_value_to_nu_value(v: &nu_json::Value, tag: impl Into<Tag>) -> Value {
let tag = tag.into();
let span = tag.span;
2019-07-09 06:31:26 +02:00
2019-05-28 06:00:00 +02:00
match v {
nu_json::Value::Null => UntaggedValue::Primitive(Primitive::Nothing).into_value(&tag),
nu_json::Value::Bool(b) => UntaggedValue::boolean(*b).into_value(&tag),
nu_json::Value::F64(n) => UntaggedValue::decimal_from_float(*n, span).into_value(&tag),
nu_json::Value::U64(n) => UntaggedValue::int(*n).into_value(&tag),
nu_json::Value::I64(n) => UntaggedValue::int(*n).into_value(&tag),
nu_json::Value::String(s) => {
UntaggedValue::Primitive(Primitive::String(String::from(s))).into_value(&tag)
2019-07-09 06:31:26 +02:00
}
nu_json::Value::Array(a) => UntaggedValue::Table(
2019-06-03 09:41:28 +02:00
a.iter()
.map(|x| convert_json_value_to_nu_value(x, &tag))
2019-06-03 09:41:28 +02:00
.collect(),
2019-07-09 06:31:26 +02:00
)
.into_value(tag),
nu_json::Value::Object(o) => {
let mut collected = TaggedDictBuilder::new(&tag);
2019-05-28 06:00:00 +02:00
for (k, v) in o.iter() {
collected.insert_value(k.clone(), convert_json_value_to_nu_value(v, &tag));
2019-05-28 06:00:00 +02:00
}
2019-07-09 06:31:26 +02:00
collected.into_value()
2019-05-28 06:00:00 +02:00
}
}
}
pub fn from_json_string_to_value(s: String, tag: impl Into<Tag>) -> nu_json::Result<Value> {
let v: nu_json::Value = nu_json::from_str(&s)?;
Ok(convert_json_value_to_nu_value(&v, tag))
2019-06-01 21:20:48 +02:00
}
fn from_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name_tag = args.call_info.name_tag.clone();
2019-07-24 00:22:11 +02:00
let args = args.evaluate_once()?;
let objects = args.has_flag("objects");
let concat_string = args.input.collect_string(name_tag.clone())?;
2019-08-27 13:05:51 +02:00
let string_clone: Vec<_> = concat_string.item.lines().map(|x| x.to_string()).collect();
if objects {
Ok(string_clone
.into_iter()
.filter_map(move |json_str| {
2019-08-27 13:05:51 +02:00
if json_str.is_empty() {
return None;
2019-08-27 13:05:51 +02:00
}
match from_json_string_to_value(json_str, &name_tag) {
Ok(x) => Some(x),
Err(e) => {
let mut message = "Could not parse as JSON (".to_string();
message.push_str(&e.to_string());
message.push(')');
Some(Value::error(ShellError::labeled_error_with_secondary(
message,
"input cannot be parsed as JSON",
name_tag.clone(),
"value originates from here",
concat_string.tag.clone(),
)))
2019-08-24 09:38:38 +02:00
}
}
})
.to_output_stream())
} else {
match from_json_string_to_value(concat_string.item, name_tag.clone()) {
Ok(x) => match x {
Value {
value: UntaggedValue::Table(list),
..
} => Ok(list.into_iter().to_output_stream()),
x => Ok(OutputStream::one(x)),
},
Err(e) => {
let mut message = "Could not parse as JSON (".to_string();
message.push_str(&e.to_string());
message.push(')');
Ok(OutputStream::one(Value::error(
ShellError::labeled_error_with_secondary(
message,
"input cannot be parsed as JSON",
name_tag,
"value originates from here",
concat_string.tag,
),
)))
2019-08-27 13:05:51 +02:00
}
2019-08-21 08:39:57 +02:00
}
}
2019-05-28 06:00:00 +02:00
}
#[cfg(test)]
mod tests {
use super::FromJson;
use super::ShellError;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
test_examples(FromJson {})
}
}