1
0

json_parse_agent.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. module Agents
  2. class JsonParseAgent < Agent
  3. include FormConfigurable
  4. cannot_be_scheduled!
  5. description <<-MD
  6. The JSON Parse Agent parses a JSON string and emits the data in a new event
  7. `data` is the JSON to parse. Use [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) templating to specify the JSON string.
  8. `data_key` sets the key which contains the parsed JSON data in emitted events
  9. MD
  10. def default_options
  11. {
  12. 'data' => '{{ data }}',
  13. 'data_key' => 'data',
  14. }
  15. end
  16. event_description do
  17. "Events will looks like this:\n\n %s" % Utils.pretty_print(interpolated['data_key'] => {parsed: 'object'})
  18. end
  19. form_configurable :data
  20. form_configurable :data_key
  21. def validate_options
  22. errors.add(:base, "data needs to be present") if options['data'].blank?
  23. errors.add(:base, "data_key needs to be present") if options['data_key'].blank?
  24. end
  25. def working?
  26. received_event_without_error?
  27. end
  28. def receive(incoming_events)
  29. incoming_events.each do |event|
  30. begin
  31. mo = interpolated(event)
  32. create_event payload: { mo['data_key'] => JSON.parse(mo['data']) }
  33. rescue JSON::JSONError => e
  34. error("Could not parse JSON: #{e.class} '#{e.message}'")
  35. end
  36. end
  37. end
  38. end
  39. end