Smithy JSON

0.2.2 · active · verified Fri Apr 17

smithy-json provides robust JSON serialization and deserialization capabilities specifically for Smithy tooling within the Python ecosystem. It allows conversion between Smithy's abstract syntax tree (AST) representation (Nodes) and JSON strings. As part of the broader `smithy-python` project, it currently stands at version 0.2.2 and undergoes active development with frequent releases aligning with the main project.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a Smithy `Node` object (representing a JSON structure) and then use `smithy_json.emitters.JsonEmitter` to serialize it into a JSON string. This process is central to generating JSON based on Smithy models.

import io
from smithy_python_types.main import Node
from smithy_json.emitters import JsonEmitter

# Create a Smithy Node representing a complex JSON object
node = Node.object({
    "greeting": Node.string("Hello, Smithy!"),
    "count": Node.number(123),
    "enabled": Node.boolean(True),
    "items": Node.array([
        Node.string("item1"),
        Node.object({"id": Node.number(1)}),
        Node.null()
    ])
})

# Instantiate the JSON Emitter
emitter = JsonEmitter()

# Create a buffer to write the JSON output to
output_buffer = io.BytesIO()

# Emit the Node as JSON into the buffer
emitter.emit(node, output_buffer)

# Get the bytes from the buffer and decode to a string
json_output = output_buffer.getvalue().decode('utf-8')

print("Generated JSON:")
print(json_output)

# Example of parsing (optional)
# from smithy_json.parser import JsonParser
# parser = JsonParser()
# input_json = b'{"parsed_key": "parsed_value"}'
# parsed_node = parser.parse(io.BytesIO(input_json))
# print("\nParsed Node:", parsed_node)

view raw JSON →