gpt4 book ai didi

json - golang yaml 支持 jsonlines

转载 作者:IT王子 更新时间:2023-10-29 02:19:41 26 4
gpt4 key购买 nike

我一直在尝试获取 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{})

}
}
}

最佳答案

jsonlines 是换行分隔的 JSON。这意味着单行是 JSON,但不是多行,当然也不是多行的整个文件。

您需要一次读取一行输入的 jsonlines,并且您应该能够使用 go yaml 处理这些行,因为 YAML 是 JSON 的超集。

由于您的测试中似乎也有 YAML end of indicator (---) 行,您也需要处理这些。

关于json - golang yaml 支持 jsonlines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54809898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com