Standard library · Encoding and data

encoding/serde

Detecting the format of a piece of text and converting JSON, YAML, TOML, XML and CSV into one another.

import encoding.serde

This package reads text in one format, turns it into a Value and writes it out in another. The format names are the short strings json, yaml, toml, xml and csv.

Constants and variables

FormatUnknown

const FormatUnknown: i32 = 0
An unknown format.
encoding-serde-Transcode.salam
import encoding.serde

func main:
    data := `{"name": "salam", "port": 8080, "tags": ["a", "b"]}`
    println serde.Detect(data), serde.Detect("a: 1\nb: 2\n"), serde.Detect("<a/>"), serde.Detect("[x]\ny = 1\n"), serde.Detect("a,b\n1,2\n")
    println serde.DetectFormat(data) == serde.FormatJSON, serde.FormatUnknown, serde.FormatYAML, serde.FormatTOML, serde.FormatXML, serde.FormatCSV
    println serde.Transcode(data, "json", "yaml")
    println serde.Transcode(data, "json", "toml")
    println serde.Transcode("name,age\nAli,30\n", "csv", "json")
    mut ok := false
    _ := serde.TranscodeStrict(data, "json", "pdf", ok)
    println ok
end
Outputjson yaml xml toml csv true 0 2 3 4 5 tags: - a - b name: salam port: 8080 tags = ["a", "b"] name = "salam" port = 8080 [{"age": "30", "name": "Ali"}] false

Functions

DetectFormat

func DetectFormat(text: str): int
Guesses which format the text is in from how it looks and returns its number.

The example for this item is shown with the ones above: encoding-serde-Transcode.salam

Detect

func Detect(text: str): str
The same, but it returns the format's short name.

The example for this item is shown with the ones above: encoding-serde-Transcode.salam

TranscodeStrict

func TranscodeStrict(data: str, from: str, dest: str, ok &: bool): str
Converts text from the from format to dest; when reading or writing fails, or a format name is wrong, ok becomes false.

The example for this item is shown with the ones above: encoding-serde-Transcode.salam

Transcode

func Transcode(data: str, from: str, dest: str): str
Converts text from one format to another.

The example for this item is shown with the ones above: encoding-serde-Transcode.salam