title |
---|
Json |
JSON (JavaScript Object Notation) parsing, printing, and access utilities.
from "json" include Json
Json.parse("{\"currency\":\"€\",\"price\":99.99}")
print(
toString(
format=Pretty,
JsonObject([("currency", JsonString("€")), ("price", JsonNumber(99.9))])
)
)
Type declarations included in the Json module.
enum Json {
JsonNull,
JsonBoolean(Bool),
JsonNumber(Number),
JsonString(String),
JsonArray(List<Json>),
JsonObject(List<(String, Json)>),
}
Data structure representing JSON in Grain.
Examples:
assert Json.parse("{\"currency\":\"€\",\"price\":99.99}") == JsonObject([
("currency", JsonString("€")),
("price", JsonNumber(99.99)),
])
assert Json.parse("{\n\"currency\":\"€\",\n\"price\":99.99\n}") == JsonObject([
("currency", JsonString("€")),
("price", JsonNumber(99.99)),
])
enum JsonToStringError {
InvalidNumber(String),
}
Represents errors for cases where a Json
data structure cannot be represented as a
JSON string.
Variants:
InvalidNumber(String)
The Json
data structure contains a number value of NaN
, Infinity
, or -Infinity
.
enum IndentationFormat {
NoIndentation,
IndentWithTab,
IndentWithSpaces(Number),
}
Controls how indentation is output in custom formatting.
Variants:
NoIndentation
No indentation is emitted.
{
"currency": "€",
"price": 99.9
}
IndentWithTab
Tabs are emitted.
{
"currency": "€",
"price": 99.9
}
IndentWithSpaces(Number)
The desired number of spaces are emitted.
IndentWithSpaces(2)
{
"currency": "€",
"price": 99.9
}
IndentWithSpaces(4)
{
"currency": "€",
"price": 99.9
}
enum ArrayFormat {
CompactArrayEntries,
SpacedArrayEntries,
OneArrayEntryPerLine,
}
Controls how arrays are output in custom formatting.
Variants:
CompactArrayEntries
Arrays are emitted in a compact manner.
[]
[1]
[1,2,3]
SpacedArrayEntries
Arrays are emitted with spaces between elements.
[ ]
[1]
[1, 2, 3]
OneArrayEntryPerLine
Arrays are emitted with newlines and indentation between each element.
[]
[
1
]
[
1,
2,
3
]
enum ObjectFormat {
CompactObjectEntries,
SpacedObjectEntries,
OneObjectEntryPerLine,
}
Controls how objects are output in custom formatting.
Variants:
CompactObjectEntries
Objects are emitted in a compact manner.
{}
{"a":1}
{"a":1,"b":2,"c":3}
SpacedObjectEntries
Objects are emitted with spaces between entries.
{ }
{"a": 1}
{"a": 1, "b": 2, "c": 3}
OneObjectEntryPerLine
Objects are emitted with each entry on a new line.
{}
{
"a": 1
}
{
"a": 1,
"b": 2,
"c": 3
}
enum LineEnding {
NoLineEnding,
LineFeed,
CarriageReturnLineFeed,
CarriageReturn,
}
Controls how line endings are output in custom formatting.
Variants:
NoLineEnding
No line endings will be emitted.
LineFeed
A \n
will be emitted at the end of each line.
CarriageReturnLineFeed
A \r\n
will be emitted at the end of each line.
CarriageReturn
A \r
will be emitted at the end of each line.
enum FormattingChoices {
Pretty,
Compact,
PrettyAndSafe,
CompactAndSafe,
Custom{
indentation: IndentationFormat,
arrayFormat: ArrayFormat,
objectFormat: ObjectFormat,
lineEnding: LineEnding,
finishWithNewLine: Bool,
escapeAllControlPoints: Bool,
escapeHTMLUnsafeSequences: Bool,
escapeNonASCII: Bool,
},
}
Allows control of formatting in JSON output.
Variants:
Pretty
Recommended human readable formatting.
Escapes all control points for the sake of clarity, but outputs unicode codepoints directly so the result needs to be treated as proper unicode and is not safe to be transported in ASCII encoding.
Roughly Equivalent to:
Custom{
indentation: IndentWithSpaces(2),
arrayFormat: OneArrayEntryPerLine,
objectFormat: OneObjectEntryPerLine,
lineEnding: LineFeed,
finishWithNewLine: true,
escapeAllControlPoints: true,
escapeHTMLUnsafeSequences: false,
escapeNonASCII: false,
}
{
"currency": "€",
"price": 99.9,
"currencyDescription": "EURO\u007f",
}
Compact
Compact formatting that minimizes the size of resulting JSON at cost of not being easily human readable.
Only performs minimal string escaping as required by the ECMA-404 standard, so the result needs to be treated as proper unicode and is not safe to be transported in ASCII encoding.
Roughly Equivalent to:
Custom{
indentation: NoIndentation,
arrayFormat: CompactArrayEntries,
objectFormat: CompactObjectEntries,
lineEnding: NoLineEnding,
finishWithNewLine: false,
escapeAllControlPoints: false,
escapeHTMLUnsafeSequences: false,
escapeNonASCII: false,
}
{"currency":"€","price":99.9,"currencyDescription":"EURO␡"}
PrettyAndSafe
Pretty and conservative formatting to maximize compatibility and embeddability of the resulting JSON.
Should be safe to copy and paste directly into HTML and to be transported in plain ASCII.
Roughly Equivalent to:
Custom{
indentation: IndentWithSpaces(2),
arrayFormat: OneArrayEntryPerLine,
objectFormat: OneObjectEntryPerLine,
lineEnding: LineFeed,
finishWithNewLine: true,
escapeAllControlPoints: true,
escapeHTMLUnsafeSequences: true,
escapeNonASCII: true,
}
{
"currency": "\u20ac",
"price": 99.9,
"currencyDescription": "EURO\u007f",
}
CompactAndSafe
Compact and conservative formatting to maximize compatibility and embeddability of the resulting JSON.
Should be safe to copy and paste directly into HTML and to transported in plain ASCII.
Roughly Equivalent to:
Custom{
indentation: NoIndentation,
arrayFormat: CompactArrayEntries,
objectFormat: CompactObjectEntries,
lineEnding: NoLineEnding,
finishWithNewLine: false,
escapeAllControlPoints: true,
escapeHTMLUnsafeSequences: true,
escapeNonASCII: true,
}
{"currency":"\u20ac","price":99.9,"currencyDescription":"EURO\u007f"}
Custom{
indentation: IndentationFormat,
arrayFormat: ArrayFormat,
objectFormat: ObjectFormat,
lineEnding: LineEnding,
finishWithNewLine: Bool,
escapeAllControlPoints: Bool,
escapeHTMLUnsafeSequences: Bool,
escapeNonASCII: Bool,
}
Allows for fined grained control of the formatting output.
enum JsonParseError {
UnexpectedEndOfInput(String),
UnexpectedToken(String),
InvalidUTF16SurrogatePair(String),
}
Represents errors for JSON parsing along with a human readable message.
Functions and constants included in the Json module.
Added in next
No other changes yet.
toString :
(?format: FormattingChoices, json: Json) =>
Result<String, JsonToStringError>
Converts the Json
data structure into a JSON string with specific formatting settings.
Parameters:
param | type | description |
---|---|---|
?format |
FormattingChoices |
Formatting options |
json |
Json |
The Json data structure to convert |
Returns:
type | description |
---|---|
Result<String, JsonToStringError> |
Ok(str) containing the JSON string or Err(err) if the provided Json data structure cannot be converted to a string |
Examples:
assert toString(
JsonObject([("currency", JsonString("€")), ("price", JsonNumber(99.9))]
) == Ok("{\"currency\":\"€\",\"price\":99.9}")
assert toString(
format=Compact
JsonObject([("currency", JsonString("€")), ("price", JsonNumber(99.9))])
) == Ok("{\"currency\":\"€\",\"price\":99.9}")
assert toString(
format=Pretty,
JsonObject([("currency", JsonString("€")), ("price", JsonNumber(99.9))])
) == Ok("{
\"currency\": \"€\",
\"price\": 99.9
}")
assert toString(
format=Custom{
indentation: NoIndentation,
arrayFormat: CompactArrayEntries,
objectFormat: CompactObjectEntries,
lineEnding: NoLineEnding,
finishWithNewLine: false,
escapeAllControlPoints: true,
escapeHTMLUnsafeSequences: true,
escapeNonASCII: true,
},
JsonObject([("currency", JsonString("€")), ("price", JsonNumber(99.9))])
) == Ok("{\"currency\":\"\\u20ac\",\"price\":99.9}")
Added in next
No other changes yet.
parse : (str: String) => Result<Json, JsonParseError>
Parses JSON string into a Json
data structure.
Parameters:
param | type | description |
---|---|---|
str |
String |
The JSON string to parse |
Returns:
type | description |
---|---|
Result<Json, JsonParseError> |
Ok(json) containing the parsed data structure on a successful parse or Err(err) containing a parse error otherwise |
Examples:
assert parse("{\"currency\":\"$\",\"price\":119}") == Ok(
JsonObject([
("currency", JsonString("$")),
("price", JsonNumber(119))
])
)