Golang:从文本文件中读取无效的JSON

时间:2015-05-05 08:18:33

标签: json go

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

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

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

它有+300个Entry值。我想阅读该文件并提取属于端口部分的 id 值。它不是有效的JSON所以我不能使用json解码器,有没有其他方法来提取值?

2 个答案:

答案 0 :(得分:1)

如果整个结构是相同的,你想要的只是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

不是在循环中打印它们,而是将它们粘贴到切片或贴图中,或者做任何你想要/需要的东西。当然,而不是使用您在文件中的行中读取的字符串文字。

答案 1 :(得分:1)

我相信text/scanner在这里可能非常有用。它不是即插即用的,但它允许你标记输入并很好地解析你的字符串(空格,转义值等)。快速概念验证,扫描仪使用简单的状态机来捕获id: {str}部分中的所有Entry模式:

var s scanner.Scanner
s.Init(strings.NewReader(src))

// Keep state of parsing process
const (
    StateNone = iota
    StateID
    StateIDColon
)
state := StateNone

lastToken := ""        // last token text
sections := []string{} // section stack

tok := s.Scan()
for tok != scanner.EOF {
    txt := s.TokenText()
    switch txt {
    case "id":
        if state == StateNone {
            state = StateID
        } else {
            state = StateNone
        }
    case ":":
        if state == StateID {
            state = StateIDColon
        } else {
            state = StateNone
        }
    case "{":
        // Add section
        sections = append(sections, lastToken)
    case "}":
        // Remove section
        if len(sections) > 0 {
            sections = sections[0 : len(sections)-1]    
        }
    default:
        if state == StateIDColon && sections[0] == "port" {
            // Our string is here
            fmt.Println(txt)
        }
        state = StateNone
    }
    lastToken = txt
    tok = s.Scan()
}

你可以play it here。如果你需要验证输入结构等,这肯定需要更多的工作,但对我来说似乎是一个很好的起点。