rss2json/src/json_lib.rs
2024-07-14 23:22:14 +02:00

69 lines
2.1 KiB
Rust

use chrono::DateTime;
use json::{object, JsonValue};
use log::error;
use rss::Channel;
pub fn build_json(channel: Channel) -> JsonValue {
// Initialize root object with channel informations, using object macro from json crate
let mut data = object! {
channel: object!{
title: channel.title(),
link: channel.link(),
description: channel.description(),
last_build_date: channel.last_build_date(),
language: channel.language(),
copyright: channel.copyright(),
generator: channel.generator()
}
};
// declare an mutable array to populate it with channel item data
let mut items_data = json::JsonValue::new_array();
// populate the items array
for item in channel.items() {
let pub_datetime = DateTime::parse_from_rfc2822(item.pub_date().unwrap()).unwrap();
// create object to hold item data
let mut item_data = object! {
title: item.title(),
link: item.link(),
pub_date: item.pub_date(),
pub_ts: pub_datetime.timestamp(),
description: item.description(),
// author: item.author()
};
// populate categories
let mut categories = json::JsonValue::new_array();
for category in item.categories() {
match categories.push(category.name()) {
Ok(_) => {}
Err(e) => {
// memory overflow ? as a beginner, style puzzled by rust
error!("Error pushing to items_data {}", e);
}
}
}
item_data["categories"] = categories;
if item.content().is_some() {
item_data["content"] = json::JsonValue::String(item.content().unwrap().to_string());
}
match items_data.push(item_data) {
Ok(_) => {}
Err(e) => {
// memory overflow ? as a beginner, style puzzled by rust
error!("Error pushing to items_data {}", e);
}
}
}
// attach the items to the json data root
data["items"] = items_data;
return data;
}