Repository navigation
JSON Conversion
The ronjson package converts between RON and JSON. It is also what the CLI commands to-json and from-json use.
import "github.com/peltonapp/rustyon-go/ronjson"| Function | Description |
|---|---|
ToJSON(src []byte, indent string) ([]byte, error) |
RON document to JSON. An empty indent gives compact output. |
ValueToJSON(v rustyon.Value, indent string) ([]byte, error) |
Value tree to JSON. |
FromJSON(src []byte, opts Options) ([]byte, error) |
JSON document to RON text. |
JSONToValue(src []byte, opts Options) (rustyon.Value, error) |
JSON document to a value tree. |
type Options struct {
// Structs writes JSON objects whose keys are all valid identifiers as
// RON structs (key: value) instead of maps {"key": value}.
Structs bool
// Indent pretty prints the output with the given indent. An empty
// Indent produces compact output.
Indent string
}Options.Indent is only used by FromJSON.
RON is richer than JSON, so the conversion loses information:
| RON | JSON |
|---|---|
() |
null |
None |
null |
Some(v) |
v |
true, false
|
true, false
|
| integer (up to 128 bits) | number with all digits |
| float | number |
NaN, inf, -inf
|
error |
| string | string |
char 'c'
|
string "c"
|
identifier Red (unit variant or unit struct) |
string "Red"
|
byte string b"\x01\x02"
|
array of numbers [1,2]
|
| list, tuple, named tuple | array; the name is dropped |
| struct, named struct | object in field order; the name is dropped |
| map | object in entry order |
Map keys become strings:
| RON key | JSON key |
|---|---|
| string, char, identifier | its text |
| integer, float, bool | its text, for example "1", "2.5", "true"
|
() |
"()" |
None |
"None" |
Some(k) |
the key k
|
| list, map, struct, tuple, byte string | error |
Object key order and integer precision are preserved. Enum variants lose their names: Circle(radius: 2.5) becomes {"radius": 2.5} and Circle(1.0) becomes [1].
src := []byte(`GameConfig(
title: "Rusty Game",
size: (800, 600),
fps: Some(60),
icon: None,
difficulty: Hard,
spawn: Circle(radius: 2.5),
initial: 'R',
blob: b"\x01\x02",
keys: {"up": Up, 1: One, true: Yes},
seed: 340282366920938463463374607431768211455,
)`)
out, err := ronjson.ToJSON(src, " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out)){
"title": "Rusty Game",
"size": [
800,
600
],
"fps": 60,
"icon": null,
"difficulty": "Hard",
"spawn": {
"radius": 2.5
},
"initial": "R",
"blob": [
1,
2
],
"keys": {
"up": "Up",
"1": "One",
"true": "Yes"
},
"seed": 340282366920938463463374607431768211455
}Note that a 128-bit integer is valid JSON, but many JSON readers (including JavaScript) cannot hold it without losing precision.
Errors:
_, err := ronjson.ToJSON([]byte(`[1.0, NaN]`), "")
fmt.Println(err) // ronjson: NaN cannot be represented in JSON
_, err = ronjson.ToJSON([]byte(`{[1, 2]: "x"}`), "")
fmt.Println(err) // ronjson: a list cannot be used as a JSON object keyInvalid RON input returns a *rustyon.SyntaxError.
| JSON | RON |
|---|---|
null |
None |
true, false
|
true, false
|
number without ., e or E
|
integer, with full precision |
| other numbers | float |
| string | string |
| array | list |
| object | map with string keys, in source order |
object, with Structs: true and all keys identifiers |
anonymous struct (key: value)
|
With Structs, a key counts as an identifier if it is non-empty, starts with an ASCII letter or _ and continues with ASCII letters, digits or _. If any key fails the test, the whole object stays a map. Empty objects stay {}.
src := []byte(`{"name": "x", "tags": ["a"], "id": 12345678901234567890, "ratio": 0.5, "extra": null, "not an ident": 1}`)
out, _ := ronjson.FromJSON(src, ronjson.Options{})
fmt.Println(string(out))
// {"name":"x","tags":["a"],"id":12345678901234567890,"ratio":0.5,"extra":None,"not an ident":1}
out, _ = ronjson.FromJSON([]byte(`{"a": {"b": 1}}`), ronjson.Options{Structs: true})
fmt.Println(string(out))
// (a:(b:1))With Indent, the output is pretty printed like MarshalIndent:
out, _ := ronjson.FromJSON(src, ronjson.Options{Structs: true, Indent: " "})
fmt.Println(string(out)){
"name": "x",
"tags": [
"a",
],
"id": 12345678901234567890,
"ratio": 0.5,
"extra": None,
"not an ident": 1,
}Trailing data after the JSON value is an error (ronjson: unexpected data after JSON value), as is an empty input.
JSONToValue and ValueToJSON work on rustyon.Value trees, which is useful when you want to inspect or edit the data between formats:
v, _ := ronjson.JSONToValue([]byte(`{"n": 1, "f": 1.0}`), ronjson.Options{Structs: true})
s := v.(rustyon.Struct)
n, _ := s.Get("n")
f, _ := s.Get("f")
fmt.Println(n.Kind(), f.Kind()) // integer float
out, _ := ronjson.ValueToJSON(s, "")
fmt.Println(string(out)) // {"n":1,"f":1}The last line shows one more loss: the JSON float 1.0 is written back as 1, because JSON has no separate float syntax.
JSON to RON to JSON keeps structure, key order and integer precision. Numbers with a fraction or exponent go through float64, so their spelling can change: {"a": 1.0, "b": 1e2} comes back as {"a":1,"b":100}.
RON to JSON to RON is lossy as described above: names, chars, byte strings, Some and the difference between tuples and lists, and between structs and maps, do not survive.
rustyon is licensed under the BSD-3-Clause license. It is an independent implementation of RON and is not affiliated with the ron-rs project.