@Neeraj_Jain (Neeraj Jain) posted a new topic, subject "Logstash filter: Convert all fields in json to integer". It read:

   Hi,  
    I have a json data of below format (in rubydebug output). I want to convert all the counter values to integer. with mutate filter plugin, i have to convert each counter to integer. However, this is a shortened data. i have a lot of counters. So i tried using the ruby code.. Ruby Code show below.  
    I get error "Ruby exception occurred: no implicit conversion of String into Integer" for this ruby code. I dont think the error is for value.to_i. its something to do with "event.set(['counters']['#{key}']".
    
    > {  
    >  "@timestamp" => 2019-05-11T14:37:56.933Z,  
    >  "component-name" => "myComponent",  
    >  "counters" => {  
    >  "counter1" => "19034",  
    >  "counter2" => "90",  
    >  "counter3" => "46",  
    >  "counter4" => "11",  
    >  "counter5" => "0",  
    >  "counter6" => "0",  
    >  "counter7" => "32737",  
    >  },  
    >  "host" => "mylinushost",  
    >  "@version" => "1"  
    >  }
    [code] 
           ruby {
              code => "
                  counterdata =  event.get('[counters]')
                  counterdata.to_hash
                  counterdata.each { |key, value|
                      event.set(['counters']['#{key}'], value.to_i)
                  }
              "
          }
        
    [/code]
    
    Please help. Or is there any other option apart from ruby. Thanks

@Badger replied

    Try
    [code] 
        ruby {
            code => '
                event.get("[counters]").each { |key, value|
                    event.set("[counters][#{key}]", value.to_i)
                }
            '
        }
    [/code]

After which, @Neeraj_Jain (Neeraj Jain) added

    Hi @Badger,  
    Thanks.. That worked like a charm.
    
    ~Neeraj

Then @system (system) said

    This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.


{'source': 'discourse', 'url': 'https://discuss.elastic.co/t/logstash-filter-convert-all-fields-in-json-to-integer/180662', 'title': 'Logstash filter: Convert all fields in json to integer', 'views': 1034, 'has_accepted_answer': False, 'word_count': 192, 'like_count': 0, 'reply_count': 1, 'participant_count': 2, 'posts': 4, 'tags': '', 'author': '@Neeraj_Jain (Neeraj Jain)', 'participants': '@Neeraj_Jain (Neeraj Jain), @Badger, @system (system)', 'image_url': [None], 'created_at': '2019-05-11T16:21:58.862Z', 'last_posted_at': '2019-06-10T06:41:57.089Z'}