0

我是 Ruby 新手,我有一个 JSON 数据集,我正在使用stympy 的 Faker 对其进行去标识化。我宁愿通过引用更改 Hash 中的值。

我试过改变分配,例如。key['v] = namea[1]到,data['cachedBook']['rows'][key][value] = namea[1]但我得到一个no implicit conversion of Array into String错误。这是有道理的,因为每个本身都是一个数组,但我不确定如何进行。

单行例如data['cachedBook']['rows']如下所示:

    [{"v":"Sijpkes_PreviewUser","c":"LN","uid":"9######","iuid":"3####7","avail":true,"sortval":"Sijpkes_PreviewUser"},
{"v":"Paul","c":"FN","sortval":"Paul"},
{"v":"#####_previewuser","c":"UN"},
    {"v":"","c":"SI"},{"v":"30 June 2016","c":"LA","sortval":1467261918000},
    {"v":"Available","c":"AV"},[],[],[],[],[],[],
    {"v":"-","tv":"","numAtt":"0","c":"374595"},[],[],
    {"v":"-","tv":"","numAtt":"0","c":"374596"},[],[],[],
    {"v":0,"tv":"0.0","mp":840,"or":"y","c":"362275"},
    {"v":0,"tv":"0.0","mp":99.99999,"or":"y","c":"389721"}] 

键和值被解释为前两个条目。敏感数据已用####s 删除。

红宝石代码:

data['cachedBook']['rows'].each do |key, value|
  fullname = Faker::Name.name
  namea = fullname.split(' ')

  str = "OLD: " + String(key['v']) + " " + String(value['v']) +"\n";
  puts str

  if ["Ms.", "Mr.", "Dr.", "Miss", "Mrs."].any? { |needle| fullname.include? needle  }
      key['v'] = namea[2]
      value['v'] = namea[1]
      value['sortval'] = namea[1]
  else
      key['v'] = namea[1]
      value['v'] = namea[0]
      value['sortval'] = namea[1]
  end

  str = "\nNEW: \nFullname: "+String(fullname)+"\nConverted surname: "+ String(key['v']) + "\n\t firstname: " + String(value['v'])
  puts str
end

puts data
4

1 回答 1

0

好的,这是一个很好的学习练习!

我遇到的问题分为两部分:

  1. 来自的 JSON 输出JSON.parse是一个哈希,但哈希存储的是数组,所以我的代码被破坏了。查看上面的示例数据行,它包含一些空数组:... [],[],[] ....

  2. 我误解了 each 是如何使用 Hash 的,我假设key, value(类似于 jquery each),但key, value在原始的 each 语句中实际上评估了前两个数组元素。

所以这是我修改后的代码:

data['cachedBook']['rows'].map! { |row|
  fullname = Faker::Name.name
  namea = fullname.split(' ')

  row.each { |val|

  if val.class == Hash
      newval = val.clone
        if ["Ms.", "Mr.", "Dr.", "Miss", "Mrs."].any? { |needle| fullname.include? needle  }
              if val.key?("c") && val["c"] == "LN"
                newval["v"] = namea[1]
                newval["sortval"] = namea[1]
              end
              if val.key?("c") && val["c"] == "FN"
                newval["v"] = namea[2]
                newval["sortval"] = namea[2]
              end
        else
            if val.key?("c") && val["c"] == "LN"
              newval["v"] = namea[0]
              newval["sortval"] = namea[0]
            end
            if val.key?("c") && val["c"] == "FN"
              newval["v"] = namea[1]
              newval["sortval"] = namea[1]
            end
        end
    val.merge!(newval)
  end
  }
}
于 2016-08-10T23:24:59.960 回答