Skip to content
Chloë Strainge edited this page Oct 14, 2026 · 1 revision

JSON documents and typed mapping

Import std::json for two useful views of JSON:

  • decode produces ordinary Shelly values, suitable for immediate calculations.
  • parse produces an exact Document, retaining JSON number text and document structure.

encode serializes supported values. wrap builds an exact Document from a value.

import std::json
let $value = std::json::decode '{"name":"Juniper","visits":3}'
echo $value["name"] ($value["visits"] + 1)
echo (std::json::encode [true, (), "ready"])
Juniper 4
[true,null,"ready"]

Navigate a document

at requires a JSON Pointer path; find returns () if absent. Pointer components escape ~ as ~0 and / as ~1. Typed accessors such as require_string and require_integer validate the selected node.

import std::json
let $document = std::json::parse '{"trip":{"stops":["Pier","Hill"]}}'
echo ($document.require_string "/trip/stops/1")
echo ($document.find "/trip/missing")
Hill
()

A Document exposes kind, value, array_items, members, and count. Exact Number values expose their original text and checked numeric accessors. Use these when a numeric identifier must survive without a floating-point round trip.

Map into application types

import std::json
struct Trail { pub name: String, pub distance: Float }
let $trail: Trail = std::json::decode_as '{"name":"Ridge","distance":5}' Trail
echo $trail.name $trail.distance
Ridge 5.0

Mapping follows declared field types, including Integer-to-Float promotion. Mapping options control policy; custom struct and enum codecs support interfaces that need private representation or a different wire shape.

Parse options cover duplicate-name policy, number handling, and bounded document sizes/depths. Conversion failures are errors rather than partially accepted data.

Incremental documents

read_lines yields exact documents from JSON lines; read_array yields members of an array selected by a pointer. These return item streams. lines_source and array_source encode document streams as byte sources. read_as maps incoming documents into a requested type. Use boxed streams when JSON null must be distinguishable from the end of an iterator.

Pipeline formats provide concise JSON conversion at a pipe boundary; explicit APIs give more control over limits, exactness, and ownership.


Related: Pipeline formats · Bytes and I/O · HTTP

Clone this wiki locally