An ATProto Lexicon validator for Gleam.

add json helpers

Changed files
+56
src
+56
src/honk.gleam
··· 2 2 3 3 import argv 4 4 import gleam/dict.{type Dict} 5 + import gleam/dynamic 5 6 import gleam/dynamic/decode 6 7 import gleam/int 7 8 import gleam/io ··· 199 200 Error("Value does not match format: " <> format_name) 200 201 } 201 202 } 203 + } 204 + 205 + /// Convert a Dynamic value to Json 206 + /// 207 + /// This is useful when parsing JSON strings with `json.parse(str, decode.dynamic)` 208 + /// and then needing to convert to Json for validation. 209 + /// 210 + /// ## Example 211 + /// ```gleam 212 + /// use dyn <- result.try(json.parse(json_str, decode.dynamic)) 213 + /// use json_val <- result.try(honk.dynamic_to_json(dyn)) 214 + /// honk.validate([json_val]) 215 + /// ``` 216 + pub fn dynamic_to_json(dyn: dynamic.Dynamic) -> Result(Json, ValidationError) { 217 + json_helpers.dynamic_to_json(dyn) 218 + } 219 + 220 + /// Parse a JSON string and convert to Json for validation 221 + /// 222 + /// This is a convenience function that combines `json.parse()` and `dynamic_to_json()`. 223 + /// It's useful when you have JSON stored as strings (e.g., in a database) and want 224 + /// to validate it with honk. 225 + /// 226 + /// ## Example 227 + /// ```gleam 228 + /// use json_val <- result.try(honk.parse_json_string(stored_json)) 229 + /// honk.validate([json_val]) 230 + /// ``` 231 + pub fn parse_json_string(json_str: String) -> Result(Json, ValidationError) { 232 + use dyn <- result.try( 233 + json.parse(json_str, decode.dynamic) 234 + |> result.map_error(fn(_) { 235 + errors.invalid_schema("Failed to parse JSON string") 236 + }), 237 + ) 238 + dynamic_to_json(dyn) 239 + } 240 + 241 + /// Parse multiple JSON strings and convert to Json for validation 242 + /// 243 + /// This is a convenience function for batch parsing JSON strings. 244 + /// 245 + /// ## Example 246 + /// ```gleam 247 + /// use json_vals <- result.try(honk.parse_json_strings(stored_jsons)) 248 + /// honk.validate(json_vals) 249 + /// ``` 250 + pub fn parse_json_strings( 251 + json_strs: List(String), 252 + ) -> Result(List(Json), ValidationError) { 253 + json_strs 254 + |> list.try_map(parse_json_string) 255 + |> result.map_error(fn(_) { 256 + errors.invalid_schema("Failed to parse JSON strings") 257 + }) 202 258 } 203 259 204 260 /// CLI entry point for the honk lexicon validator