Is there a way to sort json by value in it
e.g. [{"chapter": "3"},{"chapter": "1.5"},{"chapter": "2"},{"chapter": "1"}]
Result should be [{"chapter": "1"},{"chapter": "1.5"},{"chapter": "2"},{"chapter": "3"}]
match serde_json::from_str(&manga_json) {
Ok(json_value) => match json_value {
Value::Object(obj) => {
if let Some(data_array) = obj.get("data").and_then(Value::as_array) {
// data_array is in format [{"chapter":"3"},{"chapter":"2"}]
}
}
_ => {
println!("JSON is not an object.");
}
},
Err(err) => println!("Error parsing JSON: {}", err),
}
EDIT
I forgot that chapter is in attributes
// data format is [{"attributes":{"chapter":"3"}},{"attributes":{"chapter":"2"}}]
I made this function but this its wrong
fn sort(data: &Vec<Value>) -> Vec<Value> {
let mut data_array = data.to_owned();
data_array.sort_unstable_by_key(|v| {
v.get("attributes")
.unwrap()
.get("chapter")
.and_then(Value::as_i64)
});
return data_array;
}
This is what I get when i print it
Object {"attributes": Object {"chapter": String("35")}}
But it still don't sort what am I missing
EDIT 2
fn sort(data: &Vec<Value>) -> Vec<Value> {
let mut data_array = data.to_owned();
data_array.sort_unstable_by_key(|v| {
v.get("attributes")
.unwrap()
.get("chapter")
.unwrap()
.as_f64();
});
return data_array;
This still doesn't sort.
EDIT 3
fn sort(data: &Vec<Value>) -> Vec<Value> {
let mut data_array = data.to_owned();
data_array.sort_unstable_by_key(|v| {
return v
.get("attributes")
.unwrap()
.get("chapter")
.unwrap()
.as_str()
.unwrap()
.split(".")
.next()
.unwrap()
.parse::<i32>()
.unwrap();
});
return data_array;
}
I came to conclusion that this is working and I'll leave it at that, I wanted to sort it by float number but since sort_unstable_by_key
is NOT able to process float, I would just cut the decimal part and leave it at that, if there is a way to sort it by float number, thanks in advance
FINAL EDIT
fn sort(data: &Vec<Value>) -> Vec<Value> {
let mut data_array = data.to_owned();
data_array.sort_unstable_by(|v, b| {
return v
.get("attributes")
.unwrap()
.get("chapter")
.unwrap()
.as_str()
.unwrap()
.parse::<f32>()
.unwrap()
.total_cmp(
&b.get("attributes")
.unwrap()
.get("chapter")
.unwrap()
.as_str()
.unwrap()
.parse::<f32>()
.unwrap(),
);
});
return data_array;
}
This the final function