### Importing the parsetoml library Source: https://github.com/nimparsers/parsetoml/blob/master/README.md Include the library in your Nim project. ```nim import parsetoml ``` -------------------------------- ### Construct TOML Values Programmatically Source: https://context7.com/nimparsers/parsetoml/llms.txt Creates TOML structures using explicit constructors or the concise ? operator. ```nim import parsetoml # Using explicit constructors let strVal = newTString("hello") let intVal = newTInt(42) let floatVal = newTFloat(3.14) let boolVal = newTBool(true) let nullVal = newTNull() # Create arrays var arr = newTArray() arr.add(newTInt(1)) arr.add(newTInt(2)) arr.add(newTInt(3)) # Create tables var table = newTTable() table["name"] = newTString("config") table["values"] = arr # Using the ? operator for concise construction let quickStr = ?"hello" let quickInt = ?42 let quickFloat = ?3.14 let quickBool = ?true let quickArr = ?[1, 2, 3, 4] let quickTable = ?[("key", ?"value"), ("count", ?100)] # Building complex structures var config = newTTable() config["server"] = ?[("host", ?"localhost"), ("port", ?8080)] config["features"] = ?["logging", "metrics", "tracing"] config["enabled"] = ?true echo config.toTomlString() ``` -------------------------------- ### Navigate Nested TOML Structures Source: https://context7.com/nimparsers/parsetoml/llms.txt Uses bracket operators and safe navigation procs to access nested keys and array elements. ```nim import parsetoml let config = parsetoml.parseString(""" [database] host = "localhost" port = 5432 [database.credentials] username = "admin" password = "secret" [[servers]] name = "primary" ip = "192.168.1.1" [[servers]] name = "secondary" ip = "192.168.1.2" """) # Direct bracket access (raises KeyError if missing) let host = config["database"]["host"].getStr() let port = config["database"]["port"].getInt() # Safe navigation with {} (returns nil if path doesn't exist) let username = config{"database", "credentials", "username"} if not username.isNil: echo username.getStr() # admin # Check if key exists if config["database"].hasKey("host"): echo "Host configured" if "credentials" in config["database"]: echo "Credentials present" # Access array elements by index let firstServer = config["servers"][0] echo firstServer["name"].getStr() # primary let secondServer = config["servers"][1] echo secondServer["ip"].getStr() # 192.168.1.2 # Get array length echo config["servers"].len # 2 ``` -------------------------------- ### Type Constructors - Create TOML Values Source: https://context7.com/nimparsers/parsetoml/llms.txt Provides constructors and operators for creating TOML values programmatically. ```APIDOC ## Type Constructors ### Description The library provides constructors (newTString, newTInt, newTFloat, newTBool, newTArray, newTTable, newTNull) and the generic ? operator for creating TOML values programmatically. ### Usage Example ```nim let strVal = newTString("hello") let intVal = newTInt(42) let quickTable = ?[("key", ?"value"), ("count", ?100)] ``` ``` -------------------------------- ### Type-Safe Value Retrieval with Getters Source: https://context7.com/nimparsers/parsetoml/llms.txt Utilizes getter functions like getStr, getInt, getFloat, getBool, getElems, and getTable for safe retrieval of typed TOML values. Supports optional default values for missing or mismatched types. Demonstrates basic getters, array/table access, and safe access for non-existent keys. ```nim import parsetoml let config = parsetoml.parseString(""" name = "MyApp" count = 42 ratio = 3.14159 enabled = true tags = ["web", "api", "backend"] [nested] value = "inside" """") # Basic getters with defaults let name = config["name"].getStr("unknown") # "MyApp" let count = config["count"].getInt(0) # 42 let ratio = config["ratio"].getFloat(0.0) # 3.14159 let enabled = config["enabled"].getBool(false) # true # Array access with getElems let tags = config["tags"].getElems() for tag in tags: echo tag.getStr() # Output: web, api, backend # Table access with getTable let nested = config["nested"].getTable() echo nested["value"].getStr() # Output: inside # Safe access for missing keys (returns default) let missing = config["nonexistent"].getStr("fallback") # "fallback" let missingInt = config["also_missing"].getInt(100) # 100 # Use getBiggestInt for int64 values let bigNum = config["count"].getBiggestInt(0'i64) # 42 as int64 ``` -------------------------------- ### Date and Time Types Source: https://context7.com/nimparsers/parsetoml/llms.txt Handles TOML date, time, and datetime types. ```APIDOC ## Date and Time Types ### Description Parsetoml supports TOML date, time, and datetime types with proper parsing and conversion using TomlDate, TomlTime, and TomlDateTime types. ### Usage Example ```nim let created = config["created"] echo created.kind # TomlValueKind.Datetime ``` ``` -------------------------------- ### Parse TOML from File Source: https://context7.com/nimparsers/parsetoml/llms.txt Parses a TOML file from disk using its filename or a File object. Raises IOError if the file cannot be opened. Shows accessing configuration values like host, port, and elements from an array. ```nim import parsetoml # Parse from filename let config = parsetoml.parseFile("config.toml") # Or parse from File object let f = open("config.toml", fmRead) let config2 = parsetoml.parseFile(f, "config.toml") f.close() # Access configuration values let dbHost = config["database"]["host"].getStr("localhost") let dbPort = config["database"]["port"].getInt(5432) let features = config["features"]["enabled"].getElems() echo "Connecting to ", dbHost, ":", dbPort for feature in features: echo "Feature enabled: ", feature.getStr() ``` -------------------------------- ### Dumping TOML as Nim AST Source: https://github.com/nimparsers/parsetoml/blob/master/README.md Display the parsed TOML structure in an indented Nim AST-style format. ```nim input = table file_name = string("test.txt") output = table verbose = boolean(true) ``` -------------------------------- ### toTomlString - Convert Back to TOML Format Source: https://context7.com/nimparsers/parsetoml/llms.txt Converts a TomlValueRef or TomlTableRef back to a TOML formatted string. ```APIDOC ## toTomlString ### Description Converts a `TomlValueRef` or `TomlTableRef` back to a TOML formatted string, useful for writing modified configurations back to files or generating TOML output. ### Request Example ```nim let tomlOutput = config.toTomlString() ``` ``` -------------------------------- ### Convert TOML to String Source: https://context7.com/nimparsers/parsetoml/llms.txt Converts a TomlValueRef or TomlTableRef back into a formatted TOML string. ```nim import parsetoml let config = parsetoml.parseString(""" title = "Example" version = 1 [database] host = "localhost" port = 5432 """) # Convert back to TOML string let tomlOutput = config.toTomlString() echo tomlOutput ``` -------------------------------- ### dump - Debug TOML Structure Source: https://context7.com/nimparsers/parsetoml/llms.txt Prints a human-readable representation of a TOML table structure to stdout. ```APIDOC ## dump ### Description Prints a human-readable representation of a TOML table structure to stdout, useful for debugging and understanding how TOML data is parsed internally. ### Usage Example ```nim parsetoml.dump(config.getTable()) ``` ``` -------------------------------- ### Safe Single-Key Access with getOrDefault Source: https://context7.com/nimparsers/parsetoml/llms.txt Use getOrDefault to safely access a single key from a TOML table. This method returns a default value if the key is not found, preventing nil errors. It's useful for optional configuration settings. ```nim let maybeHost = config["database"].getOrDefault("host") if not maybeHost.isNil: echo maybeHost.getStr() ``` -------------------------------- ### Parsing TOML content Source: https://github.com/nimparsers/parsetoml/blob/master/README.md Parse TOML data from strings or files into a TomlValueRef object. ```nim let table1 = parsetoml.parseString(""" [input] file_name = "test.txt" [output] verbose = true """) let table2 = parsetoml.parseFile(f) let table3 = parsetoml.parseFile("test.toml") ``` -------------------------------- ### Navigation Operators Source: https://context7.com/nimparsers/parsetoml/llms.txt Access nested values using bracket operators and safe navigation. ```APIDOC ## Navigation Operators ### Description The library provides bracket operators and utility procs for navigating through nested TOML structures, including safe access patterns that return nil for missing keys. ### Usage Example ```nim # Direct access let host = config["database"]["host"].getStr() # Safe navigation let username = config{"database", "credentials", "username"} ``` ``` -------------------------------- ### parseFile - Parse TOML from File Source: https://context7.com/nimparsers/parsetoml/llms.txt Parses a TOML file from disk and returns a TomlValueRef. Accepts either a filename string or a File object. Raises IOError if the file cannot be opened. ```APIDOC ## parseFile - Parse TOML from File ### Description Parses a TOML file from disk and returns a `TomlValueRef`. Accepts either a filename string or a `File` object. Raises `IOError` if the file cannot be opened. ### Method POST ### Endpoint /nimparsers/parsetoml/parseFile ### Parameters #### Request Body - **filePath** (string) - Required - The path to the TOML file. ### Request Example ```json { "filePath": "config.toml" } ``` ### Response #### Success Response (200) - **tomlValueRef** (object) - A reference to the parsed TOML value structure. #### Response Example ```json { "tomlValueRef": { "database": { "host": "localhost", "port": 5432 }, "features": { "enabled": ["feature1", "feature2"] } } } ``` ``` -------------------------------- ### Parse TOML File with Parsetoml Source: https://github.com/nimparsers/parsetoml/blob/master/docs/introduction.rst Use `parsetoml.parseFile` to read a TOML file into a TomlTableRef. The `parsetoml.dump` function can be used for debugging to view the internal representation of the parsed data. ```nim import parsetoml let data = parsetoml.parseFile("test.toml") parsetoml.dump(data) ``` -------------------------------- ### Handle TOML Datetime Types Source: https://context7.com/nimparsers/parsetoml/llms.txt Accesses and manipulates TOML date, time, and datetime values. ```nim import parsetoml let config = parsetoml.parseString(""" created = 2024-01-15T10:30:00Z updated = 2024-01-15T14:45:30+05:30 date_only = 2024-01-15 time_only = 10:30:00 local_datetime = 2024-01-15T10:30:00 """) # Access datetime values let created = config["created"] echo created.kind # TomlValueKind.Datetime echo $created # 2024-01-15T10:30:00Z let dateOnly = config["date_only"] echo dateOnly.kind # TomlValueKind.Date echo $dateOnly # 2024-01-15 let timeOnly = config["time_only"] echo timeOnly.kind # TomlValueKind.Time echo $timeOnly # 10:30:00 # Access datetime components if created.kind == TomlValueKind.Datetime: let dt = created.dateTimeVal echo "Year: ", dt.date.year # 2024 echo "Month: ", dt.date.month # 1 echo "Day: ", dt.date.day # 15 echo "Hour: ", dt.time.hour # 10 echo "Minute: ", dt.time.minute # 30 ``` -------------------------------- ### Debug TOML Structure Source: https://context7.com/nimparsers/parsetoml/llms.txt Prints a human-readable representation of a TOML table to stdout for debugging purposes. ```nim import parsetoml let config = parsetoml.parseString(""" [files] input = "data.txt" output = "result.txt" [[filters]] name = "trim" enabled = true [[filters]] name = "uppercase" enabled = false """) parsetoml.dump(config.getTable()) ``` -------------------------------- ### Parse TOML from String Source: https://context7.com/nimparsers/parsetoml/llms.txt Parses a string containing TOML data into a TomlValueRef. Useful for inline TOML or testing. Demonstrates accessing string, integer, boolean, float, and array of tables values, including safe access with defaults. ```nim import parsetoml let toml = parsetoml.parseString(""" [server] host = "localhost" port = 8080 debug = true [database] connection = "postgres://localhost/mydb" pool_size = 10 timeout = 30.5 [[users]] name = "admin" role = "superuser" [[users]] name = "guest" role = "readonly" """) # Access nested table values echo toml["server"]["host"].getStr() # Output: localhost echo toml["server"]["port"].getInt() # Output: 8080 echo toml["server"]["debug"].getBool() # Output: true # Access with defaults (safe for missing keys) echo toml["server"]["missing"].getStr("default_value") # Output: default_value # Access float values echo toml["database"]["timeout"].getFloat() # Output: 30.5 # Access array of tables let users = toml["users"].getElems() for user in users: echo user["name"].getStr(), " - ", user["role"].getStr() # Output: # admin - superuser # guest - readonly ``` -------------------------------- ### Parse TOML from Stream Source: https://context7.com/nimparsers/parsetoml/llms.txt Parses TOML data from any Nim stream, such as a string stream. Provides flexibility for various input sources. Demonstrates parsing from a newStringStream and accessing top-level and nested values. ```nim import parsetoml, streams # Parse from string stream let tomlContent = """ title = "My Application" version = "1.0.0" [logging] level = "info" file = "/var/log/app.log" """ let strStream = newStringStream(tomlContent) let parsed = parsetoml.parseStream(strStream, "inline-config") strStream.close() echo parsed["title"].getStr() # Output: My Application echo parsed["logging"]["level"].getStr() # Output: info ``` -------------------------------- ### Accessing parsed TOML values Source: https://github.com/nimparsers/parsetoml/blob/master/README.md Retrieve specific fields from a TomlValueRef using getter procs, with optional default values. ```nim # Get the value, or fail if it is not found let verboseFlag = table1["output"]["verbose"].getBool() # You can specify a default as well let input = table1["input"]["file_name"].getStr("some_default.txt") ``` -------------------------------- ### Converting TOML to JSON Source: https://github.com/nimparsers/parsetoml/blob/master/README.md Convert a TomlValueRef into JSON nodes for validation or serialization. ```nim import parsetoml, json let table1 = parsetoml.parseString(""" [input] file_name = "test.txt" [output] verbose = true """) echo table1.toJson.pretty() ``` -------------------------------- ### Value Getters - Type-Safe Value Retrieval Source: https://context7.com/nimparsers/parsetoml/llms.txt The library provides getter functions (getStr, getInt, getFloat, getBool, getElems, getTable) for safely retrieving typed values from TOML nodes. Each getter accepts an optional default value returned when the node is nil or of a different type. ```APIDOC ## Value Getters - Type-Safe Value Retrieval ### Description The library provides getter functions (`getStr`, `getInt`, `getFloat`, `getBool`, `getElems`, `getTable`) for safely retrieving typed values from TOML nodes. Each getter accepts an optional default value returned when the node is nil or of a different type. ### Method GET ### Endpoint /nimparsers/parsetoml/getValue ### Parameters #### Query Parameters - **keyPath** (string) - Required - The path to the value within the TOML structure (e.g., "server.host"). - **type** (string) - Required - The type of value to retrieve (e.g., "string", "int", "float", "bool", "array", "table"). - **defaultValue** (any) - Optional - The default value to return if the key is not found or the type does not match. ### Response #### Success Response (200) - **value** (any) - The retrieved value of the specified type, or the default value. #### Response Example ```json { "value": "MyApp" } ``` ``` -------------------------------- ### JSON output format Source: https://github.com/nimparsers/parsetoml/blob/master/README.md The resulting JSON structure after calling toJson on a parsed TOML object. ```json { "input": { "file_name": { "type": "string", "value": "test.txt" } }, "output": { "verbose": { "type": "bool", "value": "true" } } } ``` -------------------------------- ### toJson - Convert TOML to JSON Source: https://context7.com/nimparsers/parsetoml/llms.txt Converts TOML data structures to Nim's JsonNode format, useful for serialization, API responses, or interoperability with JSON-based systems. The output follows the TOML test suite's JSON encoding format. ```APIDOC ## toJson - Convert TOML to JSON ### Description Converts TOML data structures to Nim's `JsonNode` format, useful for serialization, API responses, or interoperability with JSON-based systems. The output follows the TOML test suite's JSON encoding format. ### Method POST ### Endpoint /nimparsers/parsetoml/toJson ### Parameters #### Request Body - **tomlValueRef** (object) - Required - The TOML data structure to convert. ### Request Example ```json { "tomlValueRef": { "input": { "file_name": "test.txt" }, "output": { "verbose": true, "count": 42 } } } ``` ### Response #### Success Response (200) - **jsonNode** (object) - The JSON representation of the TOML data. #### Response Example ```json { "jsonNode": { "input": { "file_name": { "type": "string", "value": "test.txt" } }, "output": { "verbose": { "type": "boolean", "value": true }, "count": { "type": "integer", "value": 42 } } } } ``` ``` -------------------------------- ### Convert TOML to JSON Source: https://context7.com/nimparsers/parsetoml/llms.txt Converts TOML data structures to Nim's JsonNode format using the toJson method. Useful for serialization and interoperability. The output adheres to the TOML test suite's JSON encoding format. ```nim import parsetoml, json let toml = parsetoml.parseString(""" [input] file_name = "test.txt" [output] verbose = true count = 42 """) let jsonData = toml.toJson() echo jsonData.pretty() # Output: # { # "input": { # "file_name": { # "type": "string", ``` -------------------------------- ### parseStream - Parse TOML from Stream Source: https://context7.com/nimparsers/parsetoml/llms.txt Parses TOML data from any Nim stream, providing flexibility for various input sources including string streams, file streams, or custom stream implementations. ```APIDOC ## parseStream - Parse TOML from Stream ### Description Parses TOML data from any Nim stream, providing flexibility for various input sources including string streams, file streams, or custom stream implementations. ### Method POST ### Endpoint /nimparsers/parsetoml/parseStream ### Parameters #### Request Body - **stream** (object) - Required - The Nim stream containing TOML data. - **streamName** (string) - Optional - An identifier for the stream. ### Request Example ```json { "stream": "newStringStream(\"title = \\\"My Application\\\"\nversion = \\\"1.0.0\\\"\n[logging]\nlevel = \\\"info\\\"\nfile = \\\"/var/log/app.log\\\"")", "streamName": "inline-config" } ``` ### Response #### Success Response (200) - **tomlValueRef** (object) - A reference to the parsed TOML value structure. #### Response Example ```json { "tomlValueRef": { "title": "My Application", "version": "1.0.0", "logging": { "level": "info", "file": "/var/log/app.log" } } } ``` ``` -------------------------------- ### parseString - Parse TOML from String Source: https://context7.com/nimparsers/parsetoml/llms.txt Parses a string containing TOML formatted data and returns a TomlValueRef representing the parsed table structure. This is useful for parsing inline TOML content or testing. ```APIDOC ## parseString - Parse TOML from String ### Description Parses a string containing TOML formatted data and returns a `TomlValueRef` representing the parsed table structure. This is useful for parsing inline TOML content or testing. ### Method POST ### Endpoint /nimparsers/parsetoml/parseString ### Request Body - **tomlString** (string) - Required - The TOML content as a string. ### Request Example ```json { "tomlString": "[server]\nhost = \"localhost\"\nport = 8080\ndebug = true" } ``` ### Response #### Success Response (200) - **tomlValueRef** (object) - A reference to the parsed TOML value structure. #### Response Example ```json { "tomlValueRef": { "server": { "host": "localhost", "port": 8080, "debug": true } } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.