在事先不知道其结构的情况下,如何在 Go 中解析 YAML 数据?我见过的所有示例都假设您想要解码您已经知道其键的编码映射。如果你不知道 key 怎么办?如果它不是映射而是编码列表、标量或其他常见类型怎么办?
虽然我主要关心 YAML,但这里似乎该技术通常对 JSON 等有用。因为有一个用于解析结构化数据(显然是标记结构)的通用模式。
最佳答案
对于 JSON,将数据解码为 interface{}
值。使用类型断言来确定值中的内容。
var v interface{}
err := json.Unmarshal(data, &v)
if err != nil {
// handle error
}
switch v := v.(type) {
case string:
fmt.Println("string:", v)
case float64:
fmt.Println("number:", v)
case []interface{}:
fmt.Println("array:", v)
case map[string]interface{}:
fmt.Println("object:", v)
case nil:
fmt.Println("nil")
}
关于json - 在 Go 中解析不熟悉的 YAML/JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39186917/