Parse JSON input file, extract fields and write them in output file

I have an input file where each line is a JSON object like the following:

      {
         "status_code" => "200",
          "method" => "GET",
          "country" => "US",
           "field" => "something",
        }

The goal is (for each JSON record) to extract all the fields values and write them in an output file as a single line:

 "200" "GET" "US" "something"               ----> object 1
 "404" "GET" "IT" "something_2"            -----> object 2

This is my conf:

input {
  file {
    path => "path/to/input.json"
    codec => "json"
    start_position => "beginning"
  }
}


filter {
  json {
    source => "message"
  }

  mutate {
    add_field => {
      "status_code" => "%{[status_code]}"
      "method" => "%{[method]}"
      "country" => "%{[country]}"
      "field" => "%{[field]}"
    }
  }

  mutate {
    remove_field => [ "message" ]
  }

}

output {
  file {
     path => "path/to/output.txt"
     codec => line { format => "%{[status_code]} %{[method]} %{[country]} %{[field]}"  }
  }
}

which results in

%{[status_code]} %{[method]} %{[country]} %{[field]}

Any suggestion about that?
Thanks

For a file input a path must be absolute. A relative path like "path/to/input.json" will result in an error.

The example JSON you show is 6 lines, not one line, so neither codec nor filter will parse it. If it is really spread across 6 lines you will need to use a multiline codec to combine them as a single event.

If you have a JSON object on a single line then a json codec will parse it. In that case there will be no [message] field unless the JSON object contains one. So unless that is true the json filter will be a no-op.

mutate { add_field => { "status_code" => "%{[status_code]}" } }

This filter adds a [status_code] field equal to the current value of the [status_code] field (as a side effect it converts it to a string value if it is anything else). If the [status_code] field does not exist it sets the [status_code] field to "%{[status_code]}". It seems unlikely that either of these are what you want to happen.

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