2019-06-03 09:41:28 +02:00
|
|
|
use crate::object::base::OF64;
|
2019-07-03 19:37:09 +02:00
|
|
|
use crate::object::{Dictionary, Primitive, Value};
|
2019-05-28 06:00:00 +02:00
|
|
|
use crate::prelude::*;
|
|
|
|
|
2019-06-03 09:41:28 +02:00
|
|
|
fn convert_json_value_to_nu_value(v: &serde_hjson::Value) -> Value {
|
2019-05-28 06:00:00 +02:00
|
|
|
match v {
|
2019-06-22 22:46:16 +02:00
|
|
|
serde_hjson::Value::Null => Value::Primitive(Primitive::String(String::from(""))),
|
2019-06-03 09:41:28 +02:00
|
|
|
serde_hjson::Value::Bool(b) => Value::Primitive(Primitive::Boolean(*b)),
|
|
|
|
serde_hjson::Value::F64(n) => Value::Primitive(Primitive::Float(OF64::from(*n))),
|
|
|
|
serde_hjson::Value::U64(n) => Value::Primitive(Primitive::Int(*n as i64)),
|
|
|
|
serde_hjson::Value::I64(n) => Value::Primitive(Primitive::Int(*n as i64)),
|
2019-06-22 22:46:16 +02:00
|
|
|
serde_hjson::Value::String(s) => Value::Primitive(Primitive::String(String::from(s))),
|
2019-06-03 09:41:28 +02:00
|
|
|
serde_hjson::Value::Array(a) => Value::List(
|
|
|
|
a.iter()
|
2019-07-08 18:44:53 +02:00
|
|
|
.map(|x| convert_json_value_to_nu_value(x).spanned_unknown())
|
2019-06-03 09:41:28 +02:00
|
|
|
.collect(),
|
|
|
|
),
|
|
|
|
serde_hjson::Value::Object(o) => {
|
2019-05-28 06:00:00 +02:00
|
|
|
let mut collected = Dictionary::default();
|
|
|
|
for (k, v) in o.iter() {
|
2019-07-03 19:37:09 +02:00
|
|
|
collected.add(k.clone(), convert_json_value_to_nu_value(v));
|
2019-05-28 06:00:00 +02:00
|
|
|
}
|
|
|
|
Value::Object(collected)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-16 01:03:49 +02:00
|
|
|
pub fn from_json_string_to_value(s: String) -> serde_hjson::Result<Value> {
|
|
|
|
let v: serde_hjson::Value = serde_hjson::from_str(&s)?;
|
|
|
|
Ok(convert_json_value_to_nu_value(&v))
|
2019-06-01 21:20:48 +02:00
|
|
|
}
|
|
|
|
|
2019-05-28 06:00:00 +02:00
|
|
|
pub fn from_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|
|
|
let out = args.input;
|
2019-06-16 01:03:49 +02:00
|
|
|
let span = args.name_span;
|
2019-05-28 06:00:00 +02:00
|
|
|
Ok(out
|
2019-07-03 22:31:15 +02:00
|
|
|
.values
|
2019-07-08 18:44:53 +02:00
|
|
|
.map(move |a| match a.item {
|
2019-06-16 01:03:49 +02:00
|
|
|
Value::Primitive(Primitive::String(s)) => match from_json_string_to_value(s) {
|
2019-07-08 18:44:53 +02:00
|
|
|
Ok(x) => ReturnSuccess::value(x.spanned(a.span)),
|
2019-07-03 22:31:15 +02:00
|
|
|
Err(_) => Err(ShellError::maybe_labeled_error(
|
|
|
|
"Could not parse as JSON",
|
|
|
|
"piped data failed JSON parse",
|
|
|
|
span,
|
|
|
|
)),
|
2019-06-16 01:03:49 +02:00
|
|
|
},
|
2019-07-03 22:31:15 +02:00
|
|
|
_ => Err(ShellError::maybe_labeled_error(
|
2019-06-16 01:03:49 +02:00
|
|
|
"Expected string values from pipeline",
|
|
|
|
"expects strings from pipeline",
|
|
|
|
span,
|
2019-07-03 22:31:15 +02:00
|
|
|
)),
|
2019-05-28 06:00:00 +02:00
|
|
|
})
|
2019-07-03 22:31:15 +02:00
|
|
|
.to_output_stream())
|
2019-05-28 06:00:00 +02:00
|
|
|
}
|