json_test_parser

A lightweight and efficient JSON parser for MoonBit with support for parsing and stringifying JSON data

json
parser
serialization
moon add tonyfettes/json_test_parser@0.1.0
Download zip
Version
0.1.0
License
Apache-2.0
Last updated
9 months ago
Downloads
23
README

#json_test_parser

A lightweight and efficient JSON parser for MoonBit that supports parsing and stringifying JSON data.

#Features

  • ✅ Parse all JSON value types: null, boolean, number, string, array, object
  • ✅ Proper error handling with detailed error messages
  • ✅ String escape sequences including Unicode escapes (\uXXXX)
  • ✅ Number parsing with support for integers, decimals, and scientific notation
  • ✅ Convert JSON values back to JSON strings
  • ✅ Comprehensive test coverage

#Installation

Add this package to your moon.pkg.json:

{ "import": [ "tonyfettes/json_test_parser" ] }

#Usage

#Parsing JSON

///|
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")
}
}

#Stringifying JSON

///|
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")
}

#Working with Arrays

///|
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")
}
}

#Error Handling

///|
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")
}
}

#API Reference

#Types

#JsonValue

The main enum representing JSON values with variants: Null, Boolean(Bool), Number(Double), String(String), Array(Array[JsonValue]), and Object(Map[String, JsonValue]).

#ParseError

Errors that can occur during parsing: UnexpectedChar(Int, Char), UnexpectedEof, InvalidNumber(String), InvalidEscape(Char), and InvalidUnicodeEscape(String).

#Functions

#parse(input: String) -> JsonValue raise ParseError

Parses a JSON string into a JsonValue. Raises ParseError if the input is invalid.

#JsonValue::to_json_string(self: JsonValue) -> String

Converts a JsonValue back into a JSON string representation.

#Examples

#Complex Nested Structure

///|
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")
}
}

#Round-trip Conversion

///|
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")
}

#License

Apache-2.0

#
ParseError

pub(all) suberror ParseError {
UnexpectedChar(Int, Char)
UnexpectedEof
InvalidNumber(String)
InvalidEscape(Char)
InvalidUnicodeEscape(String)
}

JSON parsing errors
impl Eq for ParseError
impl Show for ParseError

#
JsonValue

pub(all) enum JsonValue {
Null
Boolean(Bool)
Number(Double)
String(String)
Array(Array[JsonValue])
Object(Map[String, JsonValue])
}

JSON Value representation
impl Eq for JsonValue
impl Show for JsonValue

#
JsonValue::to_json_string

fn JsonValue::to_json_string(self : JsonValue) -> String

Convert JsonValue to string representation

#
parse

fn parse(input : String) -> JsonValue raise ParseError

Parse a JSON string into a JsonValue