gpt4 book ai didi

json - 戈朗 : Read non valid JSON from text file

转载 作者:IT王子 更新时间:2023-10-29 02:05:22 25 4
gpt4 key购买 nike

我有一个包含以下示例数据的 txt 文件:

host{
Entry {
id: "foo"
}
Entry {
id: "bar"
}
}

port{
Entry {
id: "lorem"
}
Entry {
id: "ipsum"
}
}

它有 +300 个条目值。我想读取文件并提取属于 port 部分的 id 值。它不是有效的 JSON,所以我不能使用 json 解码器,还有其他提取值的方法吗?

最佳答案

如果结构自始至终都是一样的,而你想要的只是 id 值,你可以这样做(on the Playground):

package main

import (
"fmt"
"strings"
)

func main() {
// This will work only if ids don't have spaces
fields := strings.Fields(input1)
for i, field := range fields {
if field == "id:" {
fmt.Println("Got an id: ", fields[i+1][1:len(fields[i+1])-1])
}
}
fmt.Println()

// This will extract all strings enclosed in ""
for i1, i2 := 0, 0;; {
i := strings.Index(input2[i1:], "\"") // find the first " starting after the last match
if i > 0 { // if we found one carry on
i1 = i + 1 + i1 // set the start index to the absolute position in the string
i2 = strings.Index(input2[i1:], "\"") // find the second "
fmt.Println(input2[i1 : i1+i2]) // print the string between ""
i1 += i2 + 1 // set the new starting index to after the last match
} else { // otherwise we are done
break
}
}


// Reading the text line by line and only processing port sections
parts := []string{"port{", " Entry {", " id: \"foo bar\"", " }", " Entry {", " id: \"more foo bar\"", " }", "}"}
isPortSection := false
for _, part := range parts {
if string.HasPrefix(part, "port"){
isPortSection = true
}
if string.HasPrefix(part, "host"){
isPortSection = false
}
if isPortSection && strings.HasPrefix(strings.TrimSpace(part),"id:") {
line := strings.TrimSpace(part)
fmt.Println(line[5:len(line)-1])
}
}
}

var input1 string = `port{
Entry {
id: "foo"
}
Entry {
id: "bar"
}
}`

var input2 string = `port{
Entry {
id: "foo bar"
}
Entry {
id: "more foo bar"
}
}`

打印:

Got an id:  foo
Got an id: bar

foo bar
more foo bar

无需在循环中打印它们,您可以将它们粘贴到 slice 或 map 中,或者做任何您想要/需要做的事情。当然,不是使用您在文件行中读取的字符串文字。

关于json - 戈朗 : Read non valid JSON from text file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30047639/

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