lundi 7 septembre 2015

Hash modification issue in hash, replacing value in ruby

I would like to get rid of the value: <value> key value inside each of the attributes in the hash. And make it like this: "total_interactions": 493.667 This is how it is currently in json format.

{
    "3": {
        "total_interactions": {
            "value": 493.667
        },
        "shares": {
            "value": 334
        },
        "comments": {
            "value": 0
        },
        "likes": {
            "value": 159.66666666666666
        },
        "total_documents": 6
    },
    "4": {
        "total_interactions": {
            "value": 701
        },
        "shares": {
            "value": 300
        },
        "comments": {
            "value": 0
        },
        "likes": {
            "value": 401
        },
        "total_documents": 1
    }
}

I want it to be like this:

{
    "3": {
        "total_interactions": 493.6666666666667,
        "shares": 334,
        "comments": 0,
        "likes": 159.66666666666666,
        "total_documents": 6
    },
    "4": {
        "total_interactions": 701,
        "shares": 300,
        "comments": 0,
        "likes": 401,
        "total_documents": 1
    }
}

Here is the code that does this but I'm not sure how to get rid of the value key:

# the result_hash variable is the first hash with value: <value>
result_hash.each do |hash_item|
            hash_item.each do |key,value_hash|
                if( !value_hash.nil? )
                    value_hash.each do |k,v|
                        hash_item[key] = v
                    end
                end             
            end
        end

Aucun commentaire:

Enregistrer un commentaire