JsonWriter
- class cometa.json.json_writer.JsonWriter(json_format=JsonFormat.COMPACT)[source]
Bases:
objectProvides a API for forward-only, non-cached writing of UTF-8 encoded JSON text.
This class allows for the incremental creation of JSON documents. It manages internal state to ensure syntactically valid JSON output.
- Parameters:
json_format (JsonFormat)
- __init__(json_format=JsonFormat.COMPACT)[source]
Creates a new JSON writer instance.
- Parameters:
json_format (JsonFormat) – The desired output format (COMPACT or PRETTY). Defaults to COMPACT.
- Return type:
None
- property refcount: int
Returns the number of active references to the underlying C object.
- property encoded_size: int
Returns the current size of the encoded data in bytes.
- property context: JsonContext
Returns the current context (ROOT, OBJECT, or ARRAY).
- property last_error: str
Returns the last error message recorded for this writer.
- reset()[source]
Resets the writer, clearing all written data. The writer can be reused for new data without creating a new instance.
- Return type:
None
- encode()[source]
Finalizes the JSON encoding and returns the resulting string.
- Returns:
The generated JSON text.
- Return type:
str
- write_property_name(name)[source]
Writes a property name. Must be called within an Object context.
- Parameters:
name (str) – The property key.
- Return type:
None
- write_bool(value)[source]
Writes a boolean value (true or false).
- Parameters:
value (bool)
- Return type:
None
- write_str(value)[source]
Writes a string value. The writer handles escaping automatically.
- Parameters:
value (str) – The string content.
- Return type:
None
- write_int(value, as_string=False)[source]
Writes an integer value.
- Parameters:
value (int | BigInt) – The integer to write.
as_string (bool) – If True, writes the number as a string (e.g. “123”). Note: Very large integers (BigInts) are always written as strings by the underlying library to preserve precision.
- Return type:
None
- write_float(value, as_string=False)[source]
Writes a floating point number.
- Parameters:
value (float) – The number to write.
as_string (bool) – If True, writes the number as a quoted string.
- Return type:
None
- write_raw_value(value)[source]
Writes a raw JSON fragment directly to the output.
Warning: The caller must ensure value is valid JSON.
- Parameters:
value (str) – The raw JSON string (e.g., “[1, 2]”).
- Return type:
None
- write_json_object(obj)[source]
Writes an existing JsonObject to the stream.
- Parameters:
obj (JsonObject) – The parsed JSON object to write.
- Return type:
None
- write_bytes(data)[source]
Writes binary data as a hexadecimal string.
- Parameters:
data (bytes | Buffer) – The data to write.
- Return type:
None
- write_bech32(hrp, data)[source]
Writes binary data encoded as a Bech32 string.
- Parameters:
hrp (str) – The human-readable part (prefix).
data (bytes | Buffer) – The binary payload.
- Return type:
None