Mayur
Mayur

Reputation: 904

Splunk query for javascript object to JSON string

Thank you in advance.

I am using Winston logger for printing application logs in JSON format.

But Somehow it prints in Javascript object format without double-quotes for keys like below

{
  message: 'APP listening on 4000',
  level: 'info',
  env: 'local',
  timestamp: '2022-03-10T04:58:35.303Z'
}

While in Splunk logs it does not consider it as JSON because of missing double-quotes for Keys

Is there any Splunk query I can use runtime for this JS object to covert into JSON String with double quotes and extract fields?

Upvotes: 2

Views: 847

Answers (1)

Jerry Jeremiah
Jerry Jeremiah

Reputation: 9643

You really need to fix your import configuration so that it imports it correctly. But for events already imported you could do something crazy like this:

| rex max_match=0 "\s*(?<key>\w+): *'(?<value>[^']*)',?"
| eval json="{
  \"" . mvjoin(mvzip(key,value,"\": \""),"\",
  \"") . "\"
}"
| fields - key value

And if inline newlines don't work you coukd insert them afterward like this:

| rex max_match=0 "\s*(?<key>\w+): *'(?<value>[^']*)',?"
| eval json="{  \"" . mvjoin(mvzip(key,value,"\": \""),"\",  \"") . "\"}"
| rex mode=sed field=json "s/,/,\n/g"
| rex mode=sed field=json "s/{/{\n/g"
| rex mode=sed field=json "s/}/\n}/g"
| fields - key value

That uses a regex to extract the lines with keys and values, and then joins them back up with appropriate delimiters and then inserts newlines where they need to be.

You can try it without events by putting this at the start instead of your normal search parameters:

| makeresults
| eval _raw="{
  message: 'APP listening on 4000',
  level: 'info',
  env: 'local',
  timestamp: '2022-03-10T04:58:35.303Z'
}"
| table _raw

Upvotes: 2

Related Questions