gpt4 book ai didi

JSON 文件到 Ruby 哈希

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:59 24 4
gpt4 key购买 nike

我有一个由机器人名称及其参数和配置组成的 JSON 文件,它看起来像这样:

{
"csv-collector": {
"parameters": {
"delete_file": false,
"feed": "FileCollector",
"provider": "ola",
"path": "/tmp/",
"postfix": ".csv",
"rate_limit": 300
},
"group": "Collector",
"name": "Fileinput",
"module": "abc",
"description": "Fileinput collector fetches data from a file."
},
"csv-parser": {
"parameters": {
"columns": "classification.type,destination.ip",
"default_url_protocol": "http://",
"delimiter": ",",
"skip_header": true,
"type": "c&c"
},
"group": "Parser",
"name": "Generic CSV",
"module": "efg",
"description": "Generic CSV Parser is a generic bot"
}
}

我想将其解析为 Ruby 哈希,其中机器人名称“csv-collector”和“csv-parser”作为键,其余内容作为值。像这样:

my_hash = {"csv-collector" => {"parameters": {
"delete_file": false,
"feed": "FileCollector",
"provider": "ola",
"path": "/tmp/",
"postfix": ".csv",
"rate_limit": 300
},
"group": "Collector",
"name": "Fileinput",
"module": "abc",
"description": "Fileinput collector fetches data from a file."
}
}

我有几个机器人,所以这对其他机器人也一定有效。

我已经有以下代码:

require "json"

def read_file
temp = Hash.new
file = JSON.parse(File.read('mybotsfile.conf'))
file.each { |bot| temp << bot}
puts temp
end

但是给我以下错误:

`undefined method `<<' for {}:Hash (NoMethodErr`or)

我是 Ruby 的新手,我不太了解如何将 JSON 文件解析为 Ruby 哈希

最佳答案

require 'json'
file = File.read('your-json-file.json')
result_hash = JSON.parse(file)

关于JSON 文件到 Ruby 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42159389/

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