【问题标题】:How can I extract fields from JSON only when three matching fields are present?仅当存在三个匹配字段时,如何从 JSON 中提取字段?
【发布时间】:2016-10-22 06:18:44
【问题描述】:

我想提取 employeidresult 其中 deptcodeNameposition em> 存在。

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

【问题讨论】:

  • 是对象还是字符串的第一个sn-p?
  • 对于初学者来说,你可能想去掉标题中的“xml”,因为它真的很混乱。然后,您可能希望通过解析结构化实体来停止滥用正则表达式。最后但并非最不重要的一点是,您可能希望分享您收到的错误消息和遇到的问题。
  • 毕竟在sn-p中也没有任何正则表达式的踪迹。
  • 另外,请不要怪 ruby​​ 不了解,太可笑了。
  • @mudasobwa 请在下面找到代码 egx =/regpattern/ #这是正则表达式模式 dataMap = Array.new dataMap = msg.split("\r\n") msg is the value i am getting the result i= 0 长度 = dataMap.length 而 i

标签: json ruby hash conditional field


【解决方案1】:

通过哈希键提取字段

如果您有一个有效的 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."}]

这适用于您更正的语料库。如果你有一个结果数组或一个深度嵌套的结构,那么你需要做一些额外的编码来使它工作。但是,它适用于原始帖子中给出的重构数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多