json/write_json_marshal

Code

odin_info.odin ¶
59 linesSource

1/*
2Demonstrates how you can turn a struct into JSON and then write that JSON out
3to a file.
4*/
5package main
6
7import "base:builtin"
8import "base:runtime"
9import "core:encoding/json"
10import "core:fmt"
11import "core:os"
12
13main :: proc() {
14	fmt.println("Some of Odin's builtin constants")
15	path := len(os.args) > 1 ? os.args[1] : "odin_info.json"
16
17	// This uses an "anonymous struct type". You could equally well do
18	//
19	//     info := Odin_Info { ODIN_OS, ODIN_ARCH, ... }
20	//
21	// where you make a struct type `Odin_Info` that contains the same fields.
22	info: struct {
23		ODIN_OS:      runtime.Odin_OS_Type,
24		ODIN_ARCH:    runtime.Odin_Arch_Type,
25		ODIN_ENDIAN:  runtime.Odin_Endian_Type,
26		ODIN_VENDOR:  string,
27		ODIN_VERSION: string,
28		ODIN_ROOT:    string,
29		ODIN_DEBUG:   bool,
30	} = {ODIN_OS, ODIN_ARCH, ODIN_ENDIAN, ODIN_VENDOR, ODIN_VERSION, ODIN_ROOT, ODIN_DEBUG}
31
32	fmt.println("Odin:")
33	fmt.printfln("%#v", info)
34
35	json_data, err := json.marshal(info, {
36		// Adds indentation etc
37		pretty         = true,
38
39		// Output enum member names instead of numeric value.
40		use_enum_names = true,
41	})
42
43	if err != nil {
44		fmt.eprintfln("Unable to marshal JSON: %v", err)
45		os.exit(1)
46	}
47
48	fmt.println("JSON:")
49	fmt.printfln("%s", json_data)
50	fmt.printfln("Writing: %s", path)
51	werr := os.write_entire_file(path, json_data)
52
53	if werr != nil {
54		fmt.eprintfln("Unable to write file: %v", werr)
55		os.exit(1)
56	}
57
58	fmt.println("Done")
59}

Declarations Used 10