### Custom Enum Serialization with jsony Source: https://context7.com/treeform/jsony/llms.txt This example shows how to define custom serialization logic for Nim enums. A dump hook is used to convert enum variants into specific string representations (e.g., 'ACTIVE', 'INACTIVE') when serializing to JSON. ```nim import jsony type Status = enum Active, Inactive, Pending proc dumpHook(s: var string, v: Status) = s.add '"' case v of Active: s.add "ACTIVE" of Inactive: s.add "INACTIVE" of Pending: s.add "PENDING" s.add '"' echo Active.toJson() ``` -------------------------------- ### Exclude Fields from Serialization with jsony (skipHook) Source: https://context7.com/treeform/jsony/llms.txt This example demonstrates how to use `skipHook` to prevent specific fields from being included during JSON serialization. It's useful for excluding sensitive data like passwords or internal state, ensuring only relevant information is exposed. ```nim import jsony type User = object id: int username: string password: string # Should never be serialized email: string proc skipHook(T: typedesc[User], key: static string): bool = key == "password" let user = User(id: 1, username: "alice", password: "secret123", email: "alice@example.com") echo user.toJson() # Output: {"id":1,"username":"alice","email":"alice@example.com"} # Skip multiple fields type Session = object id: string userId: int token: string # Internal refreshToken: string # Internal expiresAt: int proc skipHook(T: typedesc[Session], key: static string): bool = key in ["token", "refreshToken"] let session = Session(id: "sess_123", userId: 1, token: "abc", refreshToken: "xyz", expiresAt: 1234567890) echo session.toJson() # Output: {"id":"sess_123","userId":1,"expiresAt":1234567890} ``` -------------------------------- ### Using newHook for Object Initialization Source: https://github.com/treeform/jsony/blob/master/README.md Uses newHook to populate default values for an object before the JSON deserialization process completes. ```nim type Foo5 = object visible: string id: string proc newHook*(foo: var Foo5) = # Populates the object before its fully deserialized. foo.visible = "yes" var s = """{"id":"123"}""" var v = s.fromJson(Foo5) doAssert v.id == "123" doAssert v.visible == "yes" ``` -------------------------------- ### Basic Serialization and Deserialization in Nim Source: https://github.com/treeform/jsony/blob/master/README.md Demonstrates the fundamental usage of toJson and fromJson to convert Nim sequences to JSON strings and vice versa. ```nim @[1, 2, 3].toJson() -> "[1,2,3]" "[1,2,3]".fromJson(seq[int]) -> @[1, 2, 3] ``` -------------------------------- ### Options and Collections Support Source: https://context7.com/treeform/jsony/llms.txt Illustrates how jsony maps null values to Option types and handles standard Nim collections like Tables and Sets. ```nim import jsony, options, tables type Profile = object name: string bio: Option[string] let p1 = """{"name": "Alice", "bio": null}""".fromJson(Profile) echo p1.bio.isNone var config = initTable[string, string]() config["host"] = "localhost" echo config.toJson() ``` -------------------------------- ### Dynamic JSON Access with JsonNode Source: https://context7.com/treeform/jsony/llms.txt Shows how to parse JSON into dynamic JsonNode structures when the schema is unknown, and how to mix dynamic nodes with statically typed objects. ```nim import jsony, json let data = """{"users": [{"name": "Alice"}, {"name": "Bob"}], "count": 2}""".fromJson() echo data["count"].getInt() echo data["users"][0]["name"].getStr() type ApiResponse = object status: string data: JsonNode let response = """{"status": "ok", "data": {"anything": "goes", "here": [1,2,3]}}""" let resp = response.fromJson(ApiResponse) echo resp.status echo resp.data["anything"].getStr() var node = newJObject() node["key"] = newJString("value") echo node.toJson() ``` -------------------------------- ### Message Routing with RawJson Source: https://context7.com/treeform/jsony/llms.txt Demonstrates efficient message routing by parsing only necessary fields and keeping the rest as RawJson for later processing or forwarding. ```nim type Event = object eventType: string data: RawJson let events = """[ {"eventType": "user.created", "data": {"userId": 1}}, {"eventType": "order.placed", "data": {"orderId": 99, "items": ["a", "b"]}} ]""".fromJson(seq[Event]) for event in events: case event.eventType of "user.created": type UserData = object userId: int let userData = event.data.string.fromJson(UserData) of "order.placed": echo "Order data: ", event.data.string ``` -------------------------------- ### Using postHook for Post-Deserialization Logic Source: https://github.com/treeform/jsony/blob/master/README.md Uses postHook to execute logic after the object has been fully populated, useful for derived fields or data sanitization. ```nim type Sizer = object size: int originalSize: int proc postHook*(v: var Sizer) = v.originalSize = v.size var sizer = """{"size":10}""".fromJson(Sizer) doAssert sizer.size == 10 doAssert sizer.originalSize == 10 ``` -------------------------------- ### Initialize Default Values with newHook Source: https://context7.com/treeform/jsony/llms.txt The newHook procedure is triggered before parsing to set default values for objects. This is useful for ensuring specific fields have non-zero defaults when they are absent from the input JSON. ```nim import jsony type Settings = object theme: string fontSize: int showTips: bool proc newHook(v: var Settings) = v.theme = "dark" v.fontSize = 14 v.showTips = true let s1 = """{}""".fromJson(Settings) let s2 = """{"theme": "light", "fontSize": 16}""".fromJson(Settings) ``` -------------------------------- ### Post-Process Data with postHook Source: https://context7.com/treeform/jsony/llms.txt The postHook procedure runs after an object is fully parsed. It is ideal for calculating computed fields, performing data validation, or migrating legacy data structures. ```nim import jsony type Rectangle = object width: int height: int area: int proc postHook(v: var Rectangle) = v.area = v.width * v.height let rect = """{"width": 10, "height": 5}""".fromJson(Rectangle) ``` -------------------------------- ### Handling Missing Fields with Default Values Source: https://github.com/treeform/jsony/blob/master/README.md Shows how JSONy handles missing fields by preserving the object's default values, effectively ignoring missing data without throwing errors. ```nim type Entry1 = object color: string var s = """{"extra":"foo"}""" var v = s.fromJson(Entry1) doAssert v.color == "" ``` -------------------------------- ### Serialize OrderedTable and HashSet to JSON Source: https://context7.com/treeform/jsony/llms.txt Demonstrates how to convert Nim's OrderedTable and HashSet collections into JSON strings using the toJson method. JSONy automatically handles the preservation of insertion order for tables and array formatting for sets. ```Nim var ordered = initOrderedTable[string, int]() ordered["first"] = 1 ordered["second"] = 2 ordered["third"] = 3 echo ordered.toJson() var tags: HashSet[string] tags.incl("nim") tags.incl("json") tags.incl("fast") echo tags.toJson() ``` -------------------------------- ### Handling Case Variant Objects Source: https://context7.com/treeform/jsony/llms.txt Demonstrates support for Nim's discriminated unions (case objects), allowing automatic discriminator field handling during serialization and deserialization. ```nim import jsony type ShapeKind = enum skCircle, skRectangle Shape = object x, y: float case kind: ShapeKind of skCircle: radius: float of skRectangle: width, height: float let circle = """{"kind": "skCircle", "x": 10, "y": 20, "radius": 5}""".fromJson(Shape) echo circle.toJson() ``` -------------------------------- ### Customize Serialization with dumpHook Source: https://github.com/treeform/jsony/blob/master/README.md The dumpHook allows defining custom string representations for complex objects during the serialization process. ```nim type Fraction = object numerator: int denominator: int proc dumpHook*(s: var string, v: Fraction) = s.add '"' s.add $v.numerator s.add '/' s.add $v.denominator s.add '"' var f = Fraction(numerator: 10, denominator: 13) let s = f.toJson() ``` -------------------------------- ### Automatic Snake Case to Camel Case Conversion Source: https://github.com/treeform/jsony/blob/master/README.md Demonstrates JSONy's ability to map snake_case JSON keys to camelCase Nim object fields automatically. ```nim type Entry4 = object colorBlend: string var v = """{"colorBlend":"red"}""".fromJson(Entry4) doAssert v.colorBlend == "red" v = """{"color_blend":"red"}""".fromJson(Entry4) doAssert v.colorBlend == "red" ``` -------------------------------- ### Custom Serialization with dumpHook Source: https://context7.com/treeform/jsony/llms.txt The dumpHook procedure overrides the default serialization behavior for a type. This is useful for defining custom string representations or compressing data during the JSON generation process. ```nim import jsony type Fraction = object numerator: int denominator: int proc dumpHook(s: var string, v: Fraction) = s.add '"' s.add $v.numerator s.add '/' s.add $v.denominator s.add '"' let frac = Fraction(numerator: 3, denominator: 4) echo frac.toJson() ``` -------------------------------- ### Serialize Enum sets to JSON Source: https://context7.com/treeform/jsony/llms.txt Illustrates the serialization of Nim enum sets into JSON arrays. The library maps enum values to their string representations automatically. ```Nim type Permission = enum Read, Write, Execute var perms: set[Permission] = {Read, Write} echo perms.toJson() ``` -------------------------------- ### Deserialize JSON arrays into Sets Source: https://context7.com/treeform/jsony/llms.txt Shows how to parse a JSON string representing an array into a Nim HashSet. This process automatically handles duplicate removal during the conversion. ```Nim let setJson = "[\"apple\", \"banana\", \"apple\", \"cherry\"]" let fruits = setJson.fromJson(HashSet[string]) echo fruits.len ``` -------------------------------- ### Custom Enum Parsing with jsony (enumHook) Source: https://context7.com/treeform/jsony/llms.txt This snippet illustrates how to implement custom parsing logic for enums using `enumHook`. It allows mapping various string representations (case-insensitive, numeric strings) from JSON to specific Nim enum variants, enhancing flexibility. ```nim import jsony type Priority = enum prLow, prMedium, prHigh, prCritical proc enumHook(s: string, v: var Priority) = v = case s of "low", "LOW", "1": prLow of "medium", "MEDIUM", "2": prMedium of "high", "HIGH", "3": prHigh of "critical", "CRITICAL", "4": prCritical else: prLow echo " \"LOW\" ".fromJson(Priority) # prLow echo " \"high\" ".fromJson(Priority) # prHigh echo " \"3\" ".fromJson(Priority) # prHigh (numeric string) echo " \"CRITICAL\" ".fromJson(Priority) # prCritical type Color = enum cRed, cGreen, cBlue, cYellow proc enumHook(s: string, v: var Color) = v = case s of "red", "#FF0000": cRed of "green", "#00FF00": cGreen of "blue", "#0000FF": cBlue of "yellow", "#FFFF00": cYellow else: cRed echo " \"#00FF00\" ".fromJson(Color) # cGreen echo " \"blue\" ".fromJson(Color) # cBlue ``` -------------------------------- ### Snake Case to CamelCase Conversion Source: https://context7.com/treeform/jsony/llms.txt Explains the automatic mapping feature where jsony handles both snake_case and camelCase JSON keys to match Nim object fields. ```nim import jsony type UserProfile = object firstName: string lastName: string let camel = """{"firstName": "John", "lastName": "Doe"}""".fromJson(UserProfile) let snake = """{"first_name": "John", "last_name": "Doe"}""".fromJson(UserProfile) doAssert camel.firstName == "John" doAssert snake.firstName == "John" ``` -------------------------------- ### Bypass JSON parsing with RawJson in Nim Source: https://github.com/treeform/jsony/blob/master/README.md Demonstrates how to define a data structure using RawJson to capture unparsed JSON segments. This allows for efficient storage or delayed parsing of nested JSON objects. ```nim import jsony type Message = object id: uint64 data: RawJson let messageData = """{"id":123,"data":{"page":"base64","arr":[1,2,3]}}""" message = messageData.fromJson(Message) # make sure raw json was not parsed doAssert message.data.string == """{"page":"base64","arr":[1,2,3]}""" # make sure that dumping raw json produces same result doAssert message.toJson() == messageData ``` ```nim message.data.string.fromJson(DataPayload) ``` -------------------------------- ### Handle Arbitrary JSON with JsonNode Source: https://github.com/treeform/jsony/blob/master/README.md Integrate standard library JsonNode types within your custom objects to handle dynamic or unknown JSON structures. ```nim import jsony, json type Entry = object name: string data: JsonNode """ { "name":"json-in-json", "data":{ "random-data":"here", "number":123, "number2":123.456, "array":[1,2,3], "active":true, "null":null } }""".fromJson(Entry) ``` -------------------------------- ### Rename JSON Fields with renameHook Source: https://github.com/treeform/jsony/blob/master/README.md Use renameHook to map JSON keys that conflict with reserved keywords or naming styles to internal object fields. ```nim type Node = ref object kind: string proc renameHook*(v: var Node, fieldName: var string) = if fieldName == "type": fieldName = "kind" var node = """{"type":"root"}""".fromJson(Node) doAssert node.kind == "root" ``` -------------------------------- ### Custom Type Parsing with parseHook Source: https://context7.com/treeform/jsony/llms.txt The parseHook procedure allows for complete control over how a specific type is parsed from JSON. It is essential for handling custom string formats, dates, or non-standard JSON structures. ```nim import jsony, times, strutils proc parseHook(s: string, i: var int, v: var DateTime) = var str: string parseHook(s, i, str) v = parse(str, "yyyy-MM-dd HH:mm:ss") let timestamp = """ "2024-01-15 14:30:00" """.fromJson(DateTime) ``` -------------------------------- ### Override Parsing Logic with parseHook Source: https://github.com/treeform/jsony/blob/master/README.md The parseHook provides full control over the deserialization process, enabling custom logic for types like DateTime or transforming JSON structures into different object layouts. ```nim import jsony, times proc parseHook*(s: string, i: var int, v: var DateTime) = var str: string parseHook(s, i, str) v = parse(str, "yyyy-MM-dd hh:mm:ss") var dt = """ "2020-01-01 00:00:00" """.fromJson(DateTime) ``` -------------------------------- ### Filter Fields with skipHook Source: https://github.com/treeform/jsony/blob/master/README.md The skipHook allows conditional exclusion of specific fields during the serialization of an object. ```nim type Conn = object id: int Foo = object a: int password: string b: float conn: Conn proc skipHook*(T: typedesc[Foo], key: static string): bool = key in ["password", "conn"] var v = Foo(a:1, password: "12345", b:0.5, conn: Conn(id: 1)) let s = v.toJson() ``` -------------------------------- ### Serialize DateTime as ISO String with jsony Source: https://context7.com/treeform/jsony/llms.txt This snippet demonstrates how to serialize Nim's DateTime objects into ISO 8601 formatted strings using a custom dump hook. It ensures dates are consistently represented in the 'yyyy-MM-ddTHH:mm:ssZ' format when converted to JSON. ```nim import times import jsony proc dumpHook(s: var string, v: DateTime) = s.add '"' s.add v.format("yyyy-MM-dd'T'HH:mm:ss'Z'") s.add '"' let now = dateTime(2024, mJan, 15, 14, 30, 0) echo now.toJson() ``` -------------------------------- ### Customize Enum Parsing with enumHook Source: https://github.com/treeform/jsony/blob/master/README.md The enumHook allows mapping external JSON string values to internal Nim enum variants, which is useful when JSON names differ from Nim naming conventions. ```nim type Color2 = enum c2Red c2Blue c2Green proc enumHook*(s: string, v: var Color2) = v = case s: of "RED": c2Red of "BLUE": c2Blue of "GREEN": c2Green else: c2Red doAssert """ "RED" """.fromJson(Color2) == c2Red doAssert """ "BLUE" """.fromJson(Color2) == c2Blue doAssert """ "GREEN" """.fromJson(Color2) == c2Green ``` -------------------------------- ### Generate Compile-Time JSON with toStaticJson in Nim Source: https://context7.com/treeform/jsony/llms.txt The toStaticJson function allows for the generation of JSON strings during compilation, enabling zero-runtime-cost constants for static configurations. ```nim import jsony const defaultConfig = Config(version: "1.0.0") const configJson = defaultConfig.toStaticJson() static: doAssert [1, 2, 3].toStaticJson() == "[1,2,3]" ``` -------------------------------- ### Raw JSON Passthrough with jsony (RawJson) Source: https://context7.com/treeform/jsony/llms.txt This snippet shows how to use the `RawJson` type to store unparsed JSON strings directly within Nim objects. This is beneficial for handling variable JSON structures, avoiding unnecessary parsing overhead, or forwarding JSON data without modification. ```nim import jsony type Message = object id: int payload: RawJson # Not parsed, stored as-is let json = "{\"id\": 123, \"payload\": {\"nested\": {\"deeply\": [1,2,3]}, \"key\": \"value\"}}" let msg = json.fromJson(Message) # payload is stored as raw string, not parsed echo msg.payload.string # Output: {"nested":{"deeply":[1,2,3]},"key":"value"} # Re-serialize produces identical output echo msg.toJson() # Output: {"id":123,"payload":{"nested":{"deeply":[1,2,3]},"key":"value"}} # Parse RawJson later when needed type Nested = object key: string let nested = msg.payload.string.fromJson(Nested) # nested.key = "value" ``` -------------------------------- ### Serialize Objects to JSON with toJson in Nim Source: https://context7.com/treeform/jsony/llms.txt The toJson function converts Nim objects, tables, and options into JSON strings. It handles nested structures, nil references, and standard types automatically. ```nim import jsony let product = Product(id: 1, name: "Widget", price: 19.99) echo product.toJson() # Tables and Options import tables, options echo settings.toJson() echo some(42).toJson() ``` -------------------------------- ### Deserialize JSON to Objects with fromJson in Nim Source: https://context7.com/treeform/jsony/llms.txt The fromJson function converts JSON strings into Nim objects, sequences, or primitives. It automatically ignores extra fields and preserves default values for missing fields. ```nim import jsony # Basic parsing let numbers = "[1, 2, 3]".fromJson(seq[int]) let user = "{\"name\": \"Alice\", \"age\": 30}".fromJson(User) # Nested objects let person = personJson.fromJson(Person) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.