The JSON module provides comprehensive JSON (JavaScript Object Notation) capabilities for Soul, including parsing, serialization, and validation. It offers both Soul-style and JavaScript-style aliases for familiar API usage.
soul safeJsonEncode(data) { result = JSON.encode(data) if (result.type() == "ERROR") { println("Failed to encode JSON: " + result) return null } return result}// Only LIST and MAP types can be encodedvalidData = {key: "value"}encoded = safeJsonEncode(validData)println(encoded) // {"key":"value"}
Always validate before parsing: Use isValid() to check JSON validity before parsing
Handle errors gracefully: Check for ERROR types when parsing or encoding
Use appropriate aliases: Choose decode/encode or parse/stringify based on your preference
Be aware of type limitations: Only LIST and MAP types can be encoded to JSON
Consider memory usage: Large JSON strings can consume significant memory
Copy
Ask AI
// Good - validate before parsingsoul parseJsonSafely(jsonString) { if (!JSON.isValid(jsonString)) { return null } return JSON.decode(jsonString)}// Good - handle different input typessoul toJson(data) { type = data.type() if (type != "LIST" && type != "MAP") { // Wrap in a map if not directly serializable return JSON.encode({value: data}) } return JSON.encode(data)}// Good - parse with default valuessoul parseWithDefaults(jsonString, defaults) { if (!JSON.isValid(jsonString)) { return defaults } parsed = JSON.decode(jsonString) // Merge with defaults result = {} for (key in defaults) { result[key] = parsed[key] || defaults[key] } return result}
The JSON module provides essential tools for working with JSON data in Soul, enabling seamless integration with APIs, configuration files, and data exchange formats commonly used in modern applications.