std.json
Parsing and generating of JSON.
Parsing JSON
This module provides support for parsing and generating JSON, conforming to
RFC 8259 (https://www.rfc-editor.org/rfc/rfc8259). Tests were performed
against the test corpus provided by the article
https://seriot.ch/projects/parsing_json.html. Extensions such as parsing
NaN
, Infinity
, and comments are not supported.
The easiest way to parse JSON is using Json.parse
:
import std.io (buffer)
import std.json (Json)
Json.parse(Buffer.new('[10]')).get # => Json.Array([Json.Int(10)])
The parser enforces limits on the number of nested objects and the size of
strings. These limits can be adjusted by using the Parser
type directly like
so:
import std.io (Buffer)
import std.json (Parser)
let parser = Parser.new(Buffer.new('[10]'))
parser.max_depth = 4
parser.max_string_size = 128
parser.parse
Generating JSON
Generating JSON strings is done using Json.to_string
and
Json.to_pretty_string
:
import std.json (Json)
Json.Array([Json.Int(1), Json.Int(2)]).to_string # => '[1, 2]'
When using to_pretty_string
, the default indentation is two spaces per
indentation level. You can change this value by using the Generator
type
directly:
import std.json (Generator, Json)
let val = Json.Array([Json.Int(1), Json.Int(2)])
let gen = Generator.new(indent: 4)
gen.generate(val)
This would then produce the following JSON:
[
1,
2
]
Performance
The implementation provided by this module isn't optimised for maximum performance or optimal memory usage. Instead this module aims to provide an implementation that's good enough for most cases.
Classes
Error | A type describing an error produced while parsing a JSON document. | |
ErrorKind | A type describing the different possible errors. | |
Generator | A type for turning a | |
Json | A JSON value, such as | |
Number | A numeric value that's either an | |
ObjectParser | A type for parsing an object with a known set of keys. | |
Parser | A DOM parser for turning a stream of bytes into a JSON document. | |
PullParser | A pull parser for turning a stream of bytes into JSON values. | |
Query | A type used to query/fetch data from a JSON value. | |
Rule | A parsing rule defined for an | |
Type | A type describing what kind of value is located at the current position in an input stream. |