【发布时间】:2019-07-15 12:48:08
【问题描述】:
我一直在尝试让 go yaml 包解析带有 jsonlines 条目的文件。
下面是一个简单的示例,其中包含三个要解析的数据选项。
选项一是一个多文档 yaml 示例。两个文档都可以解析。
选项二是两个 jsonline 示例。第一行解析没问题,但是第二行就漏掉了。
选项三是两个 jsonline 示例,但我在两者之间放置了 yaml 文档分隔符,以强制解决问题。这两个都可以解析。
通过阅读 yaml 和 json 规范,我相信第二个选项,多个 jsonlines,应该由 yaml 解析器处理。
我的问题是:
- YAML 解析器应该处理 jsonlines 吗?
- 我是否正确使用了 go yaml 包?
package main
import (
"bytes"
"fmt"
"reflect"
"strings"
"gopkg.in/yaml.v2"
)
var testData = []string{
`
---
option_one_first_yaml_doc: ok_here
---
option_one_second_yaml_doc: ok_here
`,
`
{option_two_first_jsonl: ok_here}
{option_two_second_jsonl: missing}
`,
`
---
{option_three_first_jsonl: ok_here}
---
{option_three_second_jsonl: ok_here}
`}
func printVal(v interface{}, depth int) {
typ := reflect.TypeOf(v)
if typ == nil {
fmt.Printf(" %v\n", "<null>")
} else if typ.Kind() == reflect.Int || typ.Kind() == reflect.String {
fmt.Printf("%s%v\n", strings.Repeat(" ", depth), v)
} else if typ.Kind() == reflect.Slice {
fmt.Printf("\n")
printSlice(v.([]interface{}), depth+1)
} else if typ.Kind() == reflect.Map {
fmt.Printf("\n")
printMap(v.(map[interface{}]interface{}), depth+1)
}
}
func printMap(m map[interface{}]interface{}, depth int) {
for k, v := range m {
fmt.Printf("%sKey: %s Value(s):", strings.Repeat(" ", depth), k.(string))
printVal(v, depth+1)
}
}
func printSlice(slc []interface{}, depth int) {
for _, v := range slc {
printVal(v, depth+1)
}
}
func main() {
m := make(map[interface{}]interface{})
for _, data := range testData {
yamlData := bytes.NewReader([]byte(data))
decoder := yaml.NewDecoder(yamlData)
for decoder.Decode(&m) == nil {
printMap(m, 0)
m = make(map[interface{}]interface{})
}
}
}
【问题讨论】:
-
YAML 规范的哪一部分让你认为支持 JSONL?
-
@Volker "8.2.3 Block Nodes",在 "9.1.3 Bare Documents" 内,但我不确定,因此提出了问题。 :)
-
8.2.3 只会给你一个块节点,但不会解析 JSON。我很困惑。