A lightweight and efficient JSON parser for MoonBit with support for parsing and stringifying JSON data
{
"import": [
"tonyfettes/json_test_parser"
]
}///|
test "parse json example" {
// Parse a JSON string
let json = @json_test_parser.parse("{\"name\": \"Alice\", \"age\": 30}")
// Access the parsed data
match json {
Object(obj) => {
inspect(obj.get("name"), content="Some(String(\"Alice\"))")
inspect(obj.get("age"), content="Some(Number(30))")
}
_ => fail("Expected object")
}
}///|
test "stringify json example" {
// Create a JSON object
let obj : Map[String, @json_test_parser.JsonValue] = {
"message": @json_test_parser.JsonValue::String("Hello, World!"),
"count": @json_test_parser.JsonValue::Number(42.0),
}
let json = @json_test_parser.JsonValue::Object(obj)
// Convert to JSON string
let json_string = json.to_json_string()
// Verify it can be parsed back
let reparsed = @json_test_parser.parse(json_string)
inspect(reparsed == json, content="true")
}///|
test "parse json array" {
let json = @json_test_parser.parse("[1, 2, 3, 4, 5]")
match json {
Array(arr) => {
inspect(arr.length(), content="5")
inspect(arr[0], content="Number(1)")
}
_ => fail("Expected array")
}
}///|
test "handle parse errors" {
// Try to parse invalid JSON
let result = try! @json_test_parser.parse("{invalid")
// Check for error
match result {
Err(_) => inspect(true, content="true")
Ok(_) => fail("Should have failed")
}
}///|
test "complex structure example" {
let json_str =
#|{
#| "users": [
#| {"name": "Alice", "active": true},
#| {"name": "Bob", "active": false}
#| ],
#| "total": 2
#|}
let parsed = @json_test_parser.parse(json_str)
match parsed {
Object(root) =>
match root.get("users") {
Some(Array(users)) => inspect(users.length(), content="2")
_ => fail("Expected users array")
}
_ => fail("Expected root object")
}
}///|
test "round trip example" {
let original = @json_test_parser.JsonValue::Array([
@json_test_parser.JsonValue::String("hello"),
@json_test_parser.JsonValue::Number(123.0),
@json_test_parser.JsonValue::Boolean(true),
])
// Convert to string and back
let json_str = original.to_json_string()
let reparsed = @json_test_parser.parse(json_str)
// Should be equal
inspect(reparsed == original, content="true")
}pub(all) suberror ParseError {
UnexpectedChar(Int, Char)
UnexpectedEof
InvalidNumber(String)
InvalidEscape(Char)
InvalidUnicodeEscape(String)
}impl Eq for ParseErrorimpl Show for ParseErrorA lightweight and efficient JSON parser for MoonBit with support for parsing and stringifying JSON data