草庐IT

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

coder 2023-06-30 原文

我有一个包含以下示例数据的 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/

有关json - 戈朗 : Read non valid JSON from text file的更多相关文章

  1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  2. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

    我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

  3. ruby - 用 YAML.load 解析 json 安全吗? - 2

    我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("

  4. ruby-on-rails - Rails 渲染带有驼峰命名法的 json 对象 - 2

    我在一个简单的RailsAPI中有以下Controller代码:classApi::V1::AccountsControllerehead:not_foundendendend问题在于,生成的json具有以下格式:{id:2,name:'Simpleaccount',cash_flows:[{id:1,amount:34.3,description:'simpledescription'},{id:2,amount:1.12,description:'otherdescription'}]}我需要我生成的json是camelCase('cashFlows'而不是'cash_flows'

  5. ruby - 使用 JSON gem 将自定义对象转换为 JSON - 2

    我正在学习如何使用JSONgem解析和生成JSON。我可以轻松地创建数据哈希并将其生成为JSON;但是,在获取一个类的实例(例如Person实例)并将其所有实例变量放入哈希中以转换为JSON时,我脑袋放屁。这是我遇到问题的例子:require"json"classPersondefinitialize(name,age,address)@name=name@age=age@address=addressenddefto_jsonendendp=Person.new('JohnDoe',46,"123ElmStreet")p.to_json我想创建一个.to_json方法,这样我就可以获

  6. ruby-on-rails - 如何使用驼峰键名称从 Rails 返回 JSON - 2

    我正在构建一个带有Rails后端的JS应用程序,为了不混淆snake和camelcases,我想通过从服务器返回camelcase键名来规范化这一切。因此,当从API返回时,user.last_name将返回user.lastName。我如何实现这一点?谢谢!编辑:添加Controller代码classApi::V1::UsersController 最佳答案 我的方法是使用ActiveModelSerializer和json_api适配器:在你的Gemfile中,添加:gem'active_model_serializers'创建

  7. ruby-on-rails - 如何将数组输出为 JSON? - 2

    我有以下内容:@array.inspect["x1","x2","adad"]我希望能够将其格式化为:client.send_message(s,m,{:id=>"x1",:id=>"x2",:id=>"adad"})client.send_message(s,m,???????)如何在????????中获得@array输出?空间作为ID?谢谢 最佳答案 {:id=>"x1",:id=>"x2",:id=>"adad"}不是有效的散列,因为您有键冲突它应该是这样的:{"ids":["x1","x2","x3"]}更新:@a=["x1

  8. ruby - 使用 jbuilder 创建具有动态哈希键的 JSON - 2

    这里我想输出带有动态组名的json而不是单词组@tickets.eachdo|group,v|json.group{json.array!vdo|ticket|json.partial!'tickets/ticket',ticket:ticketend}end@ticket是这样的散列{a:[....],b:[.....]}我想要这样的输出{a:[.....],b:[....]} 最佳答案 感谢@AntarrByrd,这个问题有类似的答案:JBuilderdynamickeysformodelattributes使用上面的逻辑我已经

  9. ruby - 展平嵌套的 json 对象 - 2

    我正在寻找一种将“json”散列展平为展平散列但将路径信息保留在展平键中的方法。例如:h={"a"=>"foo","b"=>[{"c"=>"bar","d"=>["baz"]}]}flatten(h)应该返回:{"a"=>"foo","b_0_c"=>"bar","b_0_d_0"=>"baz"} 最佳答案 这应该可以解决您的问题:h={'a'=>'foo','b'=>[{'c'=>'bar','d'=>['baz']}]}moduleEnumerabledefflatten_with_path(parent_prefix=nil)

  10. ruby-on-rails - 如何计算 Ruby/Rails 中 JSON 对象的数量 - 2

    Ruby中如何“一般地”计算以下格式(有根、无根)的JSON对象的数量?一般来说,我的意思是元素可能不同(例如“标题”被称为其他东西)。没有根:{[{"title":"Post1","body":"Hello!"},{"title":"Post2","body":"Goodbye!"}]}根包裹:{"posts":[{"title":"Post1","body":"Hello!"},{"title":"Post2","body":"Goodbye!"}]} 最佳答案 首先,withoutroot代码不是有效的json格式。它将没有包

随机推荐