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

时间:2016-10-22 06:18:45

标签: json ruby hash conditional field

我想提取 employeid 结果,其中 deptcode 名称位置在场。

{
  "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

1 个答案:

答案 0 :(得分:0)

按哈希键提取字段

如果您有一个有效的JSON字符串,您可以将其转换为Ruby哈希并按键访问字段。如果存在所有字段,则使用Enumerable#all?将仅返回值。例如:

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."}]

这适用于您更正后的语料库。如果您有一系列结果或深层嵌套的结构,那么您需要进行一些额外的编码才能使其正常工作。但是,对于原始帖子中给出的重构数据,它可以正常工作。