Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
- If the schema of a TOML file is unknown,
you can parse it into a generic object (
any
ormap[string]any
). When parsing a TOML file into a generic object,map
is used for storing key-value pairs. Sincemap
is unordered, the order of keys in the original TOML file is not preserved. Using a ordered map solves the problem partly. For example, parsing a TOML file into aorderedmap.OrderedMap[string, any]
preserved the order of keys in the outer-most map but not in inner maps.
In [35]:
import "io/ioutil"
import "fmt"
import "reflect"
import "github.com/pelletier/go-toml/v2"
In [2]:
blob := []byte(`
key1 = "value1"
key2 = "value2"
key3 = "value3"
`)
var dat map[string]interface{}
toml.Unmarshal(blob, &dat)
dat
Out[2]:
In [3]:
bytes, err := ioutil.ReadFile("pyproject.toml")
bytes
Out[3]:
In [4]:
var conf map[string]interface{}
toml.Unmarshal(bytes, &conf)
conf
Out[4]:
In [5]:
reflect.TypeOf(conf)
Out[5]:
In [12]:
b, err := conf["build-system"]
b
Out[12]:
In [18]:
_, isMap := b.(map[string]interface{})
In [19]:
isMap
Out[19]:
In [21]:
_, isArr := b.([]interface{})
In [22]:
isArr
Out[22]:
In [32]:
b
Out[32]:
In [33]:
b.(map[string]interface{})["build-backend"]
Out[33]:
In [37]:
switch v := b.(type) {
case map[string]interface{}:
conf["build-system"] = v
case []interface{}:
fmt.Printf("array\n")
default:
fmt.Printf("other types")
}
In [42]:
c, err := conf["build-system"]
c
Out[42]:
In [49]:
c["build-backend"]
In [43]:
reflect.TypeOf(c)
Out[43]:
In [46]:
t, err := conf["tool"]
t
Out[46]:
In [47]:
reflect.TypeOf(t)
Out[47]:
In [48]:
t["poetry"]
In [ ]:
bm := map[string]interface{}(b)
In [7]:
reflect.TypeOf(conf["build-system"])
In [10]:
bytes, err := toml.Marshal(conf)
string(bytes)
Out[10]:
References¶
In [ ]: