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

148 lines
4.8 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, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value};
2019-05-28 06:00:00 +02:00
pub struct FromJSON;
2019-08-27 13:05:51 +02:00
#[derive(Deserialize)]
pub struct FromJSONArgs {
objects: bool,
}
2020-05-29 10:22:52 +02:00
#[async_trait]
2019-08-27 13:05:51 +02:00
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
}
async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_json(args).await
}
}
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
}
async 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 (FromJSONArgs { objects }, input) = args.process().await?;
let concat_string = input.collect_string(name_tag.clone()).await?;
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(
futures::stream::iter(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(ReturnSuccess::value(x)),
Err(e) => {
let mut message = "Could not parse as JSON (".to_string();
message.push_str(&e.to_string());
message.push(')');
Some(Err(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(
futures::stream::iter(list.into_iter().map(ReturnSuccess::value))
.to_output_stream(),
),
x => Ok(OutputStream::one(ReturnSuccess::value(x))),
},
Err(e) => {
let mut message = "Could not parse as JSON (".to_string();
message.push_str(&e.to_string());
message.push(')');
Ok(OutputStream::one(Err(
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;
2021-02-12 11:13:14 +01:00
test_examples(FromJSON {})
}
}