仅当存在三个匹配字段时,如何从JSON中提取字段?

仅当存在三个匹配字段时,如何从JSON中提取字段?,json,ruby,hash,conditional,field,Json,Ruby,Hash,Conditional,Field,我想提取deptcode、姓名和职位所在的employeid和结果 { "employeeid": 101, "result": { "deptcode": 0, "Name": "Henry", "position": "Administrator head." } } 我目前的代码是: i = beginIndex temp = "" value = "" while i < endIndex temp = da

我想提取deptcode、姓名和职位所在的employeid和结果

{
  "employeeid": 101,
  "result": {
    "deptcode": 0,
    "Name": "Henry",
    "position": "Administrator head."
  }
}
我目前的代码是:

i = beginIndex
    temp = ""
    value = ""
    while i < endIndex
      temp = dataMap[i].to_s.split(":")[1].strip()
      value += "#{temp},"
      i += 1
    end
i=beginIndex
temp=“”
value=“”
而我是
temp=dataMap[i]。到_.split(“:”[1]。strip()
值+=“#{temp},”
i+=1
结束
按哈希键提取字段 如果您有一个有效的JSON字符串,您可以将其转换为Ruby哈希并按键访问字段。使用将使您只能在所有字段都存在时返回值。例如:

require 'json'

# Use a valid JSON string, or a native Ruby hash. We'll assume you're 
# starting with a JSON string, although the following would be a valid
# Ruby hash object without parsing if not wrapped in quotes. YMMV.
json = <<~EOF
  {
    "employeeid": 101,
    "result": {
      "deptcode": 0,
      "Name": "Henry",
      "position": "Administrator head."
    }
  }
EOF

# Convert the JSON above to a Ruby hash.
hash = JSON.parse json

# Extract fields when all keys are present.
[ hash['employeeid'], hash['result'] ] if
  hash['result'].keys.all? { |key| %w[deptcode Name position].include? key }

#=> [101, {"deptcode"=>0, "Name"=>"Henry", "position"=>"Administrator head."}]
require'json'
#使用有效的JSON字符串或本机Ruby哈希。我们假设你是
#以JSON字符串开始,尽管以下内容是有效的
#Ruby哈希对象,如果没有用引号包装,则不进行解析。YMMV。
json=0,“姓名”=>“亨利”,“职位”=>“管理员负责人”。}]

这适用于您更正的语料库。如果您有一个结果数组,或者有一个深度嵌套的结构,那么您需要进行一些额外的编码以使其工作。但是,它可以很好地处理原始帖子中给出的重构数据。

是对象或字符串的第一个片段吗?对于初学者来说,您可能希望去掉标题中的“xml”,因为它确实令人困惑。然后,您可能希望停止滥用regexp解析结构化实体。最后,但并非最不重要的一点是,您可能希望分享您收到的错误消息和遇到的问题。毕竟,代码片段中也没有任何正则表达式的痕迹。此外,请不要因为您的理解不足而责怪ruby,这太荒谬了。@mudasobwa请找到下面附加的代码egx=/regpattern/#这是regex模式dataMap=Array.new dataMap=msg.split(“\r\n”)
msg是我得到结果的值
i=0 length=dataMap.length,而i