2017-10-30 16 views
0

RubyでネストされたJSON文字列内のキーのすべての出現を削除しようとしていますが、JSONの構造は予測できません。例えば、ネストされたJSON内の任意の場所でキーを削除

{ 
    "id": null, 
    "created-at": null, 
    "updated-at": null, 
    "locale": null, 
    "name": null, 
    "description": null, 
    "item": { 
    "id": null, 
    "created-at": null, 
    "updated-at": null, 
    "description": null, 
    "item-number": null, 
    "name": null 
    }, 
    "uom": { 
    "id": null, 
    "created-at": null, 
    "updated-at": null, 
    "code": null, 
    "name": null 
    } 
} 

と私は彼らが置かれているところはどこでも、「更新-AT」の出現をすべて削除します。

私はこれを試しましたが、うまくいかないようです。私は間違って何をしているポインタ誰も与えることができますか?

def strip_keys(json, targetkey) 
    json.each_with_object([]) do |record, results| 
    record.each do |key, value| 
     if value.is_a? Hash 
     results << { key => strip_keys(value, targetkey) } 
     else 
     results << { key => value } unless key == targetkey 
     end 
    end 
    end 
end 

答えて

1

のようなハッシュの配列を持っている場合、その方法はあまりにも動作します:あなたはレール(などを使用している場合

require 'json' 

file = File.read('./example.json') 
json = JSON.parse(file) 

def recursively_remove_property!(target, property) 
    target.delete_if do |k, v| 
    if k == property 
     true 
    elsif v.is_a?(Hash) 
     recursively_remove_property!(v, property) 
     false 
    end 
    end 
end 

recursively_remove_property!(json, "updated-at") 
+0

を質問タグの1つが示唆している)、[Hash#except](http://api.rubyonrails.org/classes/Hash.html#method-except)を使用する方法があるかもしれないが、私はそれを使用していない私の前に – Pend

+1

これは素晴らしく、感謝しています!関数を呼び出すときに引数を反転させてしまったのですが(recursively_remove_property!(json、 "updated-at") – p1k4blu

+0

ああ、固定されています)、私はそれをテストしていたメソッドを変更しましたが、私はここにそれを貼り付けた。それはあなたのために働いてうれしい – Pend

0
def remove_keys_deep!(h) 
    h.keys.each do |k| 
    h.delete k if [:updated-at].include? k # you can add other keys in the array to being removed 
    if h[k].kind_of?(Array) 
     h[k].each do |h2| 
     remove_keys_deep!(h2) 
     end 
    elsif h[k].kind_of?(Hash) 
     remove_keys_deep!(h[k]) 
    end 
    end 
end 

そして、

h = {...} # your hash 
remove_keys_deep!(h) 
h #=> your hash with selected keys removed 

はキーで気をつけて、それらはすべて、次のようになります。キー名か: "キー名"、両方ではありません。
ボーナス既存のJSONオブジェクトの変更を気にしない場合は、キーが

{ 
    id: 123, 
    users: [ 
    {id: 234, 
    created-at: '12/12/12' 
    }, 
    {id: 345, 
    updated-at: '11/11/11' 
    } 
    ] 
} 
関連する問題