JSON value type, tag constants, conversion helpers, parser-result types, and serialization helpers.


Tag constants

Each constant is a static Int32 tag used by JSON.

JSONNull (-- tag) Provides the null tag, value 0.
JSONInt (-- tag) Provides the signed-integer tag, value 1.
JSONReal (-- tag) Provides the real-number tag, value 2.
JSONCond (-- tag) Provides the boolean tag, value 3.
JSONString (-- tag) Provides the string tag, value 4.
JSONArray (-- tag) Provides the array tag, value 5.
JSONObject (-- tag) Provides the object tag, value 6.

JSON

JSON stores one tag and one payload. Its payload is an Int64, Real64, Cond, String, JSON Array, or String JSON HashTable.

JSON

(-- json) Constructs an owning JSONNull value.

Fields

Initialization sets the active payload to JSONNull. Assignment copies the active payload, and destruction destroys it. Parsed strings, arrays, and objects therefore belong to the containing JSON value.

Methods

For every payload getter, a runtime tag mismatch reports Wrong tag in Tagged Union! and exits with status 2 when DEBUG is enabled. With DEBUG disabled, the runtime check is omitted; do not use a wrong-payload reference.

Payload getters return borrowed views, mutable through a mutable JSON and immutable through an immutable JSON. Reacquire them after relevant tag changes or storage-moving mutations of the containing arrays or objects; do not outlive the owner.

getTag

(-- tag) Returns the stored Int32 tag.
  • Supported tags are JSONNull through JSONObject; an unsupported stored tag is returned unchanged.

setTag

(tag --) Accepts an Int32 tag and changes the active payload when it differs.
  • When the tag differs, the old payload is destroyed and the new payload is initialized; references into the old payload are no longer valid.
  • Repeating the current tag leaves the payload unchanged. Use the supported tags JSONNull through JSONObject. The range is not checked: an unsupported tag is retained, and serialization reports Unknown JSON tag!.

getInt

(-- ref) Returns a borrowed view of the active Int64 payload.
  • The active tag must be JSONInt.

getReal

(-- ref) Returns a borrowed view of the active Real64 payload.
  • The active tag must be JSONReal.

getCond

(-- ref) Returns a borrowed view of the active Cond payload.
  • The active tag must be JSONCond.

getString

(-- ref) Returns a borrowed view of the active String payload.
  • The active tag must be JSONString.

getArray

(-- ref) Returns a borrowed view of the active JSON Array payload.
  • The active tag must be JSONArray.

getObject

(-- ref) Returns a borrowed view of the active String JSON HashTable payload.
  • The active tag must be JSONObject.

Value conversions

Each conversion requires the payload schema itself: Int64, Real64, Cond, String, JSON Array, or String JSON HashTable, respectively. No implicit conversion is performed. Convert inputs first; for example, use "abc" toString stringAsJSON. Each result is a new owning JSON object. Immutable managed inputs are copied and mutable managed inputs may be moved from. intAsJSON accepts every Int64 value.

intAsJSON

(int -- json) Constructs a new owning JSON with an Int64 payload.

realAsJSON

(real -- json) Constructs a new owning JSON with a Real64 payload.

condAsJSON

(cond -- json) Constructs a new owning JSON with a Cond payload.

stringAsJSON

(string -- json) Constructs a new owning JSON with a String payload.

arrayAsJSON

(array -- json) Constructs a new owning JSON with a JSON Array payload.

objectAsJSON

(object -- json) Constructs a new owning JSON with a String JSON HashTable payload.

Payload and ownership rules


JSONParserResult

JSONParserResult

(-- result) Constructs success TRUE, finished TRUE, default errorInfo, and an owning JSONNull value.

Fields

Remarks


JSONParserPosition

JSONParserPosition

(-- position) Constructs offset 0, line 1, column 1, currentCode 0, and an empty currentSymbol view.

Fields

Remarks


JSONParserErrorInfo

JSONParserErrorInfo

(-- errorInfo) Constructs an empty owned message and default position.

Fields


Parser model and low-level helpers

Parsing runs at run time, including when source is known Text; inspect success, finished, payload, and position at run time.

Current parser limitations

Failure messages

Remarks

Low-level helpers

addrAsJSONImpl

(address -- ref) Creates a mutable JSONImpl reference at a Natx address.
  • The caller supplies storage satisfying JSON layout, alignment, extent, and lifetime. This helper neither initializes nor owns the storage.

JSONInit

(destinationAddress --) Initializes JSON storage to JSONNull.
  • destinationAddress is a Natx address of suitable uninitialized storage. The caller supplies JSON layout, alignment, extent, and lifetime; do not overwrite a live owned payload without destroying it.

JSONSet

(sourceAddress destinationAddress --) Copies the source JSON into initialized destination storage.
  • Both arguments are Natx addresses of live JSON storage. The caller supplies suitable layout, alignment, extent, and lifetime for both objects.

JSONDestroy

(destinationAddress --) Destroys the payload in initialized JSON storage.
  • destinationAddress is a Natx address of valid initialized storage. The call does not free containing storage; do not destroy the payload again without reinitializing it.

JSONImplArray

(-- array) Constructs an empty owning JSON Array.

JSONImplObject

(-- object) Constructs an empty owning String JSON HashTable.

JSONImpl

(-- impl) Constructs the internal tagged storage required by JSON.
  • data is a Variant with alternatives Cond, Int64, Real64, Cond, String, JSON Array, and String JSON HashTable in tag order. The implementation has JSON's required size and alignment.

JSONImplRef

(-- ref) Supplies a static NIL reference descriptor for JSONImpl.

makeJSONParserPosition

(code symbol offset line column -- position) Constructs a parser position from its five fields.
  • Copies or moves the five inputs into the corresponding fields: code initializes currentCode and symbol initializes currentSymbol. For the standard position schema, use Nat32, StringView, Int32, Int32, and Int32 inputs in the displayed order.

jsonInternalFillPositionChars

(source position --) Refreshes currentSymbol and currentCode from offset.
  • position.offset must be nonnegative. At or beyond the source end, the helper stores an empty view and zero; otherwise it stores the source view and its first byte.

parseJSONNodeImpl

(json result source position --) Parses one node with the low-level parser contract.
  • Use the same caller contract as parseJSONNode: mutable JSON and JSONParserResult references, a StringView Array Cref source, and a mutable JSONParserPosition reference. Initialize success and synchronize the position characters before the call; the helper does not derive finished from remaining input.

catJSONNodeWithPaddingImpl

(result padding json --) Appends one value with the serializer contract.
  • Use the same caller contract as catJSONNodeWithPadding: a mutable String reference, a nonnegative Int32 padding, and an immutable JSON view. The first token has no leading padding; nested lines use padding + 2 spaces and the closing line uses padding spaces.

impl

(-- ref) Returns a borrowed JSONImpl view of the receiver storage.
  • The view preserves receiver constness; prefer tag and payload methods for ordinary access.

parseJSONNode

(json result source position --) Parses one node from an already split source into caller-supplied JSON and JSONParserResult values.
  • json and result are mutable JSON and JSONParserResult references. source is a StringView Array Cref; position is a JSONParserPosition Ref.
  • Initialize result.success to TRUE and synchronize currentSymbol and currentCode with source and offset, using jsonInternalFillPositionChars.
  • The call writes json, updates position, and records failures in result. It does not derive finished from remaining input. The caller owns all destinations and source bytes.

catJSONNodeWithPadding

(result padding json --) Appends one JSON node to an existing String.
  • result is a String Ref, padding is a nonnegative Int32, and json is an immutable JSON view.
  • The first token has no leading padding. Nested lines use padding + 2 spaces and the closing line uses padding spaces. The call appends and returns no new String.

parseStringToJSON

parseStringToJSON

(source -- result) Parses one Text, StringView, or String source.

See the parser runtime contract.

  • The result reports lexical or JSON failure through success and errorInfo; trailing non-space input reports finished = FALSE while retaining the first node.
  • Check success before using the parsed value, and require finished for a complete-input parse. The returned result owns the parsed JSON tree.

saveJSONToString

saveJSONToString

(json -- string) Serializes the stored value using the formatting rules below.
  • Arrays preserve item order. Objects follow HashTable iteration order; that order is not a JSON key-order guarantee.
  • Objects and arrays use newlines and two spaces per nested level. Empty containers still use the container's multiline form.
  • Booleans and null are written as true, false, and null.
  • Quotes, backslashes, slashes, and the JSON control escapes are emitted with their JSON escape forms. Other code points outside printable ASCII are written as \uXXXX; supplementary code points use a high/low surrogate pair.
  • An invalid JSON tag fails with Unknown JSON tag!.

Remarks

  • Real formatting is lossy and does not preserve every Real64 value on a parse/save round trip. For example, 0.1234567890123456789 is saved as 0.123457. Integer payloads are written in decimal without this real-number rounding.
  • A non-finite JSONReal is written as inf, -inf, or nan; those spellings are not valid JSON. Require finite real payloads when valid JSON output is needed. A large parsed exponent such as 1e400 can produce infinity without a parse error.

Examples

Runtime parser results

"Json"    use
"String"  use
"control" use

{} () {} [
  result: "{\"x\":1}" parseStringToJSON;
  ("success=" result.success
    ",finished=" result.finished
    ",tag=" result.json.getTag
    ",size=" result.json.getObject.size LF) printList
  trailing: "{} x" parseStringToJSON;
  duplicate: "{\"x\":1,\"x\":2}" parseStringToJSON;
  ("trailing-success=" trailing.success
    ",finished=" trailing.finished
    ",offset=" trailing.errorInfo.position.offset LF
    "duplicate-success=" duplicate.success LF) printList
] "main" exportFunction

Expected Output

success=TRUE,finished=TRUE,tag=6,size=1
trailing-success=TRUE,finished=FALSE,offset=3
duplicate-success=FALSE

Parse and serialize array

"Json"    use
"String"  use
"control" use

{} Int32 {} [
  result: "[1,true]" parseStringToJSON;
  result.success ~ [
    1
  ] [
    result.json saveJSONToString print
    0
  ] if
] "main" exportFunction

Expected Output

[
  1,
  true
]

See also