FileParser<T>
Trait used for parsing files in different formats, such as JSON and plain text.
trait FileParser<T, +Serde<T>> {
fn parse_txt(file: @File) -> Option<T>;
fn parse_json(file: @File) -> Option<T>;
}
âšī¸ Info
Specific rules must be followed for snforge to correctly parse JSON and plain text files.
Read file format rules for more.
Example
File content:
{
"age": 30,
"job": "Software Engineer",
"location": {
"city": "New York",
"country": "USA"
},
"name": "John",
"surname": "Doe"
}
Test code:
use core::array::ArrayTrait;
use core::option::OptionTrait;
use core::serde::Serde;
use snforge_std::fs::{FileParser, FileTrait};
#[derive(Debug, Serde, Drop, PartialEq)]
struct Location {
city: ByteArray,
country: ByteArray,
}
#[derive(Debug, Serde, Drop, PartialEq)]
struct User {
age: u32,
job: ByteArray,
location: Location,
name: ByteArray,
surname: ByteArray,
}
#[test]
fn parse_json_example() {
// Create an instance of `File` to be used later
let file = FileTrait::new("data/user.json");
// Parse the JSON content from the file
let content = FileParser::<User>::parse_json(@file).expect('Failed to parse JSON');
// Serialize the content to an array for comparison
let mut output_array = ArrayTrait::new();
content.serialize(ref output_array);
println!("{:?}", content);
assert!(content.name == "John");
assert!(content.location.country == "USA");
assert!(content.age == 30);
}
Let's run the test:
$ snforge test parse_json_example
Output:
Collected 1 test(s) from snforge_library_reference package
Running 1 test(s) from tests/
User { age: 30, job: "Software Engineer", location: Location { city: "New York", country: "USA" }, name: "John", surname: "Doe" }
[PASS] snforge_library_reference_integrationtest::test_fs_parse_json::parse_json_example ([..])
Running 0 test(s) from src/
Tests: 1 passed, 0 failed, 0 ignored, [..] filtered out