laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Rows: the keyed arrays Laravel Excel passes around, and the conversion of exported data into
//! rows (`Sheet::mapArraybleRow()` and `ArrayHelper::ensureMultipleRows()`).

use std::fmt;
use std::ops::Index;

use indexmap::IndexMap;
use serde::de::DeserializeOwned;
use serde::ser::{self, Serialize, SerializeMap, SerializeSeq, Serializer};

use crate::value::Value;

/// A row's key: a heading (with `WithHeadingRow`) or a column position starting at 0, like the
/// keys of a PHP array.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Key {
    /// A position, starting at 0.
    Index(usize),
    /// A heading, or a field name.
    Name(String),
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Index(index) => write!(f, "{index}"),
            Self::Name(name) => f.write_str(name),
        }
    }
}

impl From<usize> for Key {
    fn from(index: usize) -> Self {
        Self::Index(index)
    }
}

impl From<&str> for Key {
    fn from(name: &str) -> Self {
        Self::from(name.to_owned())
    }
}

impl From<String> for Key {
    fn from(name: String) -> Self {
        // PHP turns numeric string keys into integer keys.
        match name.parse::<usize>() {
            Ok(index) if index.to_string() == name => Self::Index(index),
            _ => Self::Name(name),
        }
    }
}

/// One row of a sheet: its values under their keys, in column order, and the row's number in the
/// sheet.
///
/// Without `WithHeadingRow`, the keys are the positions `0`, `1`, `2`.. like a PHP list. With it,
/// they are the formatted headings, such as `name` and `email`. Read values with `row["name"]` or
/// `row[0]`, or deserialize the whole row into a struct with [`Row::deserialize`].
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Row {
    cells: IndexMap<Key, Value>,
    number: u32,
    images: IndexMap<String, crate::xlsx_extras::ImageContent>,
}

impl Row {
    /// An empty row.
    pub fn new() -> Self {
        Self::default()
    }

    /// A row of `values` under the positions `0`, `1`, `2`..
    pub fn from_values(values: impl IntoIterator<Item = Value>) -> Self {
        Self {
            cells: values
                .into_iter()
                .enumerate()
                .map(|(i, v)| (Key::Index(i), v))
                .collect(),
            number: 0,
            images: IndexMap::new(),
        }
    }

    pub(crate) fn with_number(mut self, number: u32) -> Self {
        self.number = number;
        self
    }

    /// The row's number in the sheet, starting at 1: `Row::getIndex()`, and the number
    /// `RemembersRowNumber` remembers.
    pub fn row_number(&self) -> u32 {
        self.number
    }

    /// The image an `Image` column read under `key`: the `ImageContent` Laravel Excel puts in the
    /// row. The row's value under `key` is the image's file name.
    pub fn image(&self, key: &str) -> Option<&crate::xlsx_extras::ImageContent> {
        self.images.get(key)
    }

    pub(crate) fn set_image(&mut self, key: String, image: crate::xlsx_extras::ImageContent) {
        self.images.insert(key, image);
    }

    /// The value under `key`, such as `row.get("email")` or `row.get(0)`.
    pub fn get(&self, key: impl Into<Key>) -> Option<&Value> {
        self.cells.get(&key.into())
    }

    /// The value under `key`, deserialized, such as `row.value::<String>("email")`.
    pub fn value<T: DeserializeOwned>(&self, key: impl Into<Key>) -> Option<T> {
        self.get(key)
            .and_then(|value| serde_json::from_value(value.to_json()).ok())
    }

    /// The value at a position, whatever its key.
    pub fn nth(&self, index: usize) -> Option<&Value> {
        self.cells.get_index(index).map(|(_, value)| value)
    }

    /// Sets the value under `key`, appending it when the key is new.
    pub fn insert(&mut self, key: impl Into<Key>, value: impl Into<Value>) -> Option<Value> {
        self.cells.insert(key.into(), value.into())
    }

    /// Appends `value` under the next free position, like `$row[] = $value`.
    pub fn push(&mut self, value: impl Into<Value>) {
        let next = self
            .cells
            .keys()
            .filter_map(|key| match key {
                Key::Index(index) => Some(index + 1),
                Key::Name(_) => None,
            })
            .max()
            .unwrap_or(0);
        self.cells.insert(Key::Index(next), value.into());
    }

    /// Removes the value under `key`.
    pub fn remove(&mut self, key: impl Into<Key>) -> Option<Value> {
        self.cells.shift_remove(&key.into())
    }

    /// The keys, in column order.
    pub fn keys(&self) -> impl Iterator<Item = &Key> {
        self.cells.keys()
    }

    /// The values, in column order.
    pub fn values(&self) -> impl Iterator<Item = &Value> {
        self.cells.values()
    }

    /// The keys and values, in column order.
    pub fn iter(&self) -> impl Iterator<Item = (&Key, &Value)> {
        self.cells.iter()
    }

    /// The number of values.
    pub fn len(&self) -> usize {
        self.cells.len()
    }

    /// Whether the row has no values at all.
    pub fn is_empty(&self) -> bool {
        self.cells.is_empty()
    }

    /// Whether every value is empty, like `count(array_filter($row)) === 0` in Laravel Excel.
    pub fn is_blank(&self) -> bool {
        self.cells.values().all(Value::is_empty)
    }

    /// The row as a JSON object keyed by the row's keys.
    pub fn to_json(&self) -> serde_json::Map<String, serde_json::Value> {
        self.cells
            .iter()
            .map(|(key, value)| (key.to_string(), value.to_json()))
            .collect()
    }

    /// Deserializes the row into `T`, such as a struct with a field per heading.
    pub fn deserialize<T: DeserializeOwned>(&self) -> laravel::Result<T> {
        let json = if self.cells.keys().all(|key| matches!(key, Key::Index(_))) {
            serde_json::Value::Array(self.cells.values().map(Value::to_json).collect())
        } else {
            serde_json::Value::Object(self.to_json())
        };
        Ok(serde_json::from_value(json)?)
    }

    /// The values, dropping the keys.
    pub fn into_values(self) -> Vec<Value> {
        self.cells.into_values().collect()
    }
}

impl<K: Into<Key>> Index<K> for Row {
    type Output = Value;

    /// The value under `key`, or `Value::Null` when the row has no such key.
    fn index(&self, key: K) -> &Value {
        static NULL: Value = Value::Null;
        self.cells.get(&key.into()).unwrap_or(&NULL)
    }
}

impl<K: Into<Key>, V: Into<Value>> FromIterator<(K, V)> for Row {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        Self {
            cells: iter.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            number: 0,
            images: IndexMap::new(),
        }
    }
}

impl IntoIterator for Row {
    type Item = (Key, Value);
    type IntoIter = indexmap::map::IntoIter<Key, Value>;

    fn into_iter(self) -> Self::IntoIter {
        self.cells.into_iter()
    }
}

/// A row serializes as a JSON array when its keys are the positions `0`, `1`, `2`.., and as an
/// object otherwise, like `json_encode` of a PHP array.
impl Serialize for Row {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let is_list = self.cells.keys().enumerate().all(|(i, key)| *key == Key::Index(i));
        if is_list {
            let mut seq = serializer.serialize_seq(Some(self.cells.len()))?;
            for value in self.cells.values() {
                seq.serialize_element(value)?;
            }
            seq.end()
        } else {
            let mut map = serializer.serialize_map(Some(self.cells.len()))?;
            for (key, value) in &self.cells {
                map.serialize_entry(&key.to_string(), value)?;
            }
            map.end()
        }
    }
}

/// Data that becomes one or more rows of a sheet.
///
/// Every type that implements `Serialize` does: a struct or map becomes one row with a value per
/// field (a model's columns, like `attributesToArray()`), a tuple, array or `Vec` of values
/// becomes one row, and a list whose items are all lists or structs becomes several rows, like
/// `ArrayHelper::ensureMultipleRows()`. A nested list or struct inside a row is written as JSON,
/// as Laravel Excel's value binder does with nested arrays.
pub trait IntoRows {
    /// Converts the data into rows.
    fn into_rows(self) -> laravel::Result<Vec<Row>>;
}

impl<T: Serialize> IntoRows for T {
    fn into_rows(self) -> laravel::Result<Vec<Row>> {
        let node = self.serialize(NodeSerializer).map_err(laravel::Error::from)?;
        Ok(node_rows(node))
    }
}

/// Converts data into exactly one row, keeping its keys: the shape an import's `WithMapping`
/// returns.
#[doc(hidden)]
pub fn into_single_row(data: impl IntoRows) -> laravel::Result<Row> {
    let mut rows = data.into_rows()?;
    Ok(if rows.is_empty() {
        Row::new()
    } else {
        rows.swap_remove(0)
    })
}

#[derive(Debug, Clone)]
enum Node {
    Scalar(Value),
    Seq(Vec<Node>),
    Map(Vec<(String, Node)>),
}

impl Node {
    fn is_compound(&self) -> bool {
        !matches!(self, Self::Scalar(_))
    }

    fn into_json(self) -> serde_json::Value {
        match self {
            Self::Scalar(value) => value.to_json(),
            Self::Seq(items) => serde_json::Value::Array(items.into_iter().map(Self::into_json).collect()),
            Self::Map(entries) => serde_json::Value::Object(
                entries
                    .into_iter()
                    .map(|(key, value)| (key, value.into_json()))
                    .collect(),
            ),
        }
    }

    fn into_value(self) -> Value {
        match self {
            Self::Scalar(value) => value,
            compound => Value::String(compound.into_json().to_string()),
        }
    }
}

fn node_rows(node: Node) -> Vec<Row> {
    match node {
        Node::Scalar(Value::Null) => Vec::new(),
        Node::Scalar(value) => vec![Row::from_values([value])],
        Node::Seq(items) => {
            if items.iter().all(Node::is_compound) {
                items.into_iter().map(node_row).collect()
            } else {
                vec![node_row(Node::Seq(items))]
            }
        }
        Node::Map(entries) => {
            if entries.iter().all(|(_, node)| node.is_compound()) {
                entries.into_iter().map(|(_, node)| node_row(node)).collect()
            } else {
                vec![node_row(Node::Map(entries))]
            }
        }
    }
}

fn node_row(node: Node) -> Row {
    match node {
        Node::Seq(items) => Row::from_values(items.into_iter().map(Node::into_value)),
        Node::Map(entries) => entries
            .into_iter()
            .map(|(key, node)| (Key::from(key), node.into_value()))
            .collect(),
        scalar => Row::from_values([scalar.into_value()]),
    }
}

#[derive(Debug)]
struct SerializeError(String);

impl fmt::Display for SerializeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for SerializeError {}

impl ser::Error for SerializeError {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        Self(msg.to_string())
    }
}

struct NodeSerializer;

struct SeqBuilder(Vec<Node>);

struct MapBuilder {
    entries: Vec<(String, Node)>,
    key: Option<String>,
}

struct VariantSeq(&'static str, Vec<Node>);

struct VariantMap(&'static str, Vec<(String, Node)>);

type NodeResult = Result<Node, SerializeError>;

impl Serializer for NodeSerializer {
    type Ok = Node;
    type Error = SerializeError;
    type SerializeSeq = SeqBuilder;
    type SerializeTuple = SeqBuilder;
    type SerializeTupleStruct = SeqBuilder;
    type SerializeTupleVariant = VariantSeq;
    type SerializeMap = MapBuilder;
    type SerializeStruct = MapBuilder;
    type SerializeStructVariant = VariantMap;

    fn serialize_bool(self, v: bool) -> NodeResult {
        Ok(Node::Scalar(Value::Bool(v)))
    }

    fn serialize_i8(self, v: i8) -> NodeResult {
        Ok(Node::Scalar(v.into()))
    }

    fn serialize_i16(self, v: i16) -> NodeResult {
        Ok(Node::Scalar(v.into()))
    }

    fn serialize_i32(self, v: i32) -> NodeResult {
        Ok(Node::Scalar(v.into()))
    }

    fn serialize_i64(self, v: i64) -> NodeResult {
        Ok(Node::Scalar(v.into()))
    }

    fn serialize_i128(self, v: i128) -> NodeResult {
        Ok(Node::Scalar(
            i64::try_from(v).map_or(Value::Float(v as f64), Value::Int),
        ))
    }

    fn serialize_u8(self, v: u8) -> NodeResult {
        Ok(Node::Scalar(v.into()))
    }

    fn serialize_u16(self, v: u16) -> NodeResult {
        Ok(Node::Scalar(v.into()))
    }

    fn serialize_u32(self, v: u32) -> NodeResult {
        Ok(Node::Scalar(v.into()))
    }

    fn serialize_u64(self, v: u64) -> NodeResult {
        Ok(Node::Scalar(v.into()))
    }

    fn serialize_u128(self, v: u128) -> NodeResult {
        Ok(Node::Scalar(
            i64::try_from(v).map_or(Value::Float(v as f64), Value::Int),
        ))
    }

    fn serialize_f32(self, v: f32) -> NodeResult {
        Ok(Node::Scalar(Value::Float(f64::from(v))))
    }

    fn serialize_f64(self, v: f64) -> NodeResult {
        Ok(Node::Scalar(Value::Float(v)))
    }

    fn serialize_char(self, v: char) -> NodeResult {
        Ok(Node::Scalar(Value::String(v.to_string())))
    }

    fn serialize_str(self, v: &str) -> NodeResult {
        Ok(Node::Scalar(Value::String(v.to_owned())))
    }

    fn serialize_bytes(self, v: &[u8]) -> NodeResult {
        Ok(Node::Scalar(Value::String(String::from_utf8_lossy(v).into_owned())))
    }

    fn serialize_none(self) -> NodeResult {
        Ok(Node::Scalar(Value::Null))
    }

    fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> NodeResult {
        value.serialize(self)
    }

    fn serialize_unit(self) -> NodeResult {
        Ok(Node::Scalar(Value::Null))
    }

    fn serialize_unit_struct(self, _name: &'static str) -> NodeResult {
        Ok(Node::Scalar(Value::Null))
    }

    fn serialize_unit_variant(self, _name: &'static str, _index: u32, variant: &'static str) -> NodeResult {
        Ok(Node::Scalar(Value::String(variant.to_owned())))
    }

    fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _name: &'static str, value: &T) -> NodeResult {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T: ?Sized + Serialize>(
        self,
        _name: &'static str,
        _index: u32,
        variant: &'static str,
        value: &T,
    ) -> NodeResult {
        Ok(Node::Map(vec![(variant.to_owned(), value.serialize(self)?)]))
    }

    fn serialize_seq(self, len: Option<usize>) -> Result<SeqBuilder, SerializeError> {
        Ok(SeqBuilder(Vec::with_capacity(len.unwrap_or(0))))
    }

    fn serialize_tuple(self, len: usize) -> Result<SeqBuilder, SerializeError> {
        Ok(SeqBuilder(Vec::with_capacity(len)))
    }

    fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<SeqBuilder, SerializeError> {
        Ok(SeqBuilder(Vec::with_capacity(len)))
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<VariantSeq, SerializeError> {
        Ok(VariantSeq(variant, Vec::with_capacity(len)))
    }

    fn serialize_map(self, len: Option<usize>) -> Result<MapBuilder, SerializeError> {
        Ok(MapBuilder {
            entries: Vec::with_capacity(len.unwrap_or(0)),
            key: None,
        })
    }

    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<MapBuilder, SerializeError> {
        self.serialize_map(Some(len))
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<VariantMap, SerializeError> {
        Ok(VariantMap(variant, Vec::with_capacity(len)))
    }
}

impl SerializeSeq for SeqBuilder {
    type Ok = Node;
    type Error = SerializeError;

    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerializeError> {
        self.0.push(value.serialize(NodeSerializer)?);
        Ok(())
    }

    fn end(self) -> NodeResult {
        Ok(Node::Seq(self.0))
    }
}

impl ser::SerializeTuple for SeqBuilder {
    type Ok = Node;
    type Error = SerializeError;

    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerializeError> {
        SerializeSeq::serialize_element(self, value)
    }

    fn end(self) -> NodeResult {
        SerializeSeq::end(self)
    }
}

impl ser::SerializeTupleStruct for SeqBuilder {
    type Ok = Node;
    type Error = SerializeError;

    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerializeError> {
        SerializeSeq::serialize_element(self, value)
    }

    fn end(self) -> NodeResult {
        SerializeSeq::end(self)
    }
}

impl ser::SerializeTupleVariant for VariantSeq {
    type Ok = Node;
    type Error = SerializeError;

    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerializeError> {
        self.1.push(value.serialize(NodeSerializer)?);
        Ok(())
    }

    fn end(self) -> NodeResult {
        Ok(Node::Map(vec![(self.0.to_owned(), Node::Seq(self.1))]))
    }
}

impl SerializeMap for MapBuilder {
    type Ok = Node;
    type Error = SerializeError;

    fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), SerializeError> {
        let key = match key.serialize(NodeSerializer)? {
            Node::Scalar(value) => value.to_string(),
            other => other.into_json().to_string(),
        };
        self.key = Some(key);
        Ok(())
    }

    fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerializeError> {
        let key = self.key.take().unwrap_or_default();
        self.entries.push((key, value.serialize(NodeSerializer)?));
        Ok(())
    }

    fn end(self) -> NodeResult {
        Ok(Node::Map(self.entries))
    }
}

impl ser::SerializeStruct for MapBuilder {
    type Ok = Node;
    type Error = SerializeError;

    fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), SerializeError> {
        self.entries.push((key.to_owned(), value.serialize(NodeSerializer)?));
        Ok(())
    }

    fn end(self) -> NodeResult {
        Ok(Node::Map(self.entries))
    }
}

impl ser::SerializeStructVariant for VariantMap {
    type Ok = Node;
    type Error = SerializeError;

    fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), SerializeError> {
        self.1.push((key.to_owned(), value.serialize(NodeSerializer)?));
        Ok(())
    }

    fn end(self) -> NodeResult {
        Ok(Node::Map(vec![(self.0.to_owned(), Node::Map(self.1))]))
    }
}

#[cfg(test)]
mod tests {
    use serde::Serialize;

    use super::*;

    #[derive(Serialize)]
    struct User {
        id: i64,
        name: String,
        tags: Vec<String>,
    }

    #[test]
    fn a_struct_is_one_row_in_field_order() {
        let rows = User {
            id: 1,
            name: "Taylor".into(),
            tags: vec!["a".into()],
        }
        .into_rows()
        .unwrap();
        assert_eq!(rows.len(), 1);
        let keys: Vec<String> = rows[0].keys().map(ToString::to_string).collect();
        assert_eq!(keys, ["id", "name", "tags"]);
        assert_eq!(rows[0]["tags"], Value::String("[\"a\"]".into()));
    }

    #[test]
    fn lists_of_lists_are_several_rows() {
        assert_eq!(vec![vec![1, 2], vec![3, 4]].into_rows().unwrap().len(), 2);
        assert_eq!(vec![1, 2].into_rows().unwrap().len(), 1);
        assert_eq!(("a", 1, None::<i32>).into_rows().unwrap()[0].len(), 3);
        assert!(Vec::<Vec<i32>>::new().into_rows().unwrap().is_empty());
    }

    #[test]
    fn rows_serialize_as_lists_or_objects() {
        let list = Row::from_values([Value::Int(1), Value::from("a")]);
        assert_eq!(serde_json::to_string(&list).unwrap(), "[1,\"a\"]");
        let object: Row = [("name", "Taylor")].into_iter().collect();
        assert_eq!(serde_json::to_string(&object).unwrap(), "{\"name\":\"Taylor\"}");
    }
}