Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created February 16, 2022 19:27
Embed
What would you like to do?
code samples from https://news.ycombinator.com/item?id=22712441 with updates

Ok, let's say you have this json:

[{
    "name": "Kévin",
    "age": 23,
    "hired": "2005-06-03 02:12:33",
    "emails": ["kevin@foo.com", "kevin@bar.com"]
}, {
}, {
    "name": "Joël",
    "age": 32,
    "hired": "2003-01-02 12:32:11",
    "emails": ["joel@foo.com", "joel@bar.com"]
},
... other entries
]

It's very simple. Very basic. There is no trick in there: it's standard utf8, well formed, no missing value. You want to print people details in alphabetical order this way:

Joël (32) - 02/01/03:
- joel@foo.com
- joel@bar.com
Kévin (23) - 03/06/05:
- kevin@foo.com
- kevin@bar.com
... other entries
import json
import datetime as dt
with open("agenda.json") as fd:
agenda = sorted(json.load(fd), key=lambda people: people["name"])
for people in agenda:
hired = dt.datetime.fromisoformat(people["hired"])
print(f'{people["name"]} ({people["age"]}) - {hired:%d/%m/%y}:')
for email in people["emails"]:
print(f" - {email}")
use std::fs;
use anyhow::Result;
use chrono::NaiveDateTime;
use serde::*;
use serde_json;
#[derive(Deserialize)]
struct Person {
name: String,
age: u32,
hired: String,
emails: Vec<String>,
}
fn main() -> Result<()> {
let data = fs::read_to_string("agenda.json")?;
let mut people: Vec<Person> = serde_json::from_str(&data)?;
people.sort_by(|a, b| b.name.cmp(&a.name));
for person in &people {
let datetime = NaiveDateTime::parse_from_str(&person.hired, "%Y-%m-%d %H:%M:%S")?;
println!(
"{} ({}) - {}",
person.name,
person.age,
datetime.format("%d/%m/%y")
);
for email in &person.emails {
println!(" - {}", email);
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment