Search code examples
regexsplunksplunk-query

Print String array of a json payload in splunk


I need to print a string array along with one field in my json object.

The data:

{ "key1":"val1",  "key2":"value2",  "codes":["apple","mango","banana","orange"], "key3_conditional":"yes"}

My Search query:

<My search query>
| rex "\|(?<payload>[^\|]*)$"
| spath input=payload
| rex "\"codes\":\"(?<codes>[^\"]*)"
| eval is_unknown=if(isnotnull(key3_conditional), key3_conditional, "no")
| table codes, is_unknown

Desired result

codes                               | is_unknown
--------------------------------------------------
apple, mango, banana, orange        | yes

Currently, this only displays the 1st value in codes i.e. apple and I need all values of codes as comma separated. I'm supposing there is some issue with my regex. Please suggest.


Solution

  • If this data is being brought-in a JSON, you won't have to rex it out

    If not, though, the issue is your regular expression

    Try it out on regex101.com - you'll see you're only grabbing the first value because you're stopping at a literal "

    Try this instead:

    ...
    | rex field=_raw "codes\":\[(?<codes>[^\]]+)"
    | eval codes=split(replace(codes,"\"",""),",")
    

    That will make codes into a multivalue field

    If you don't care about it being multivalue, you can just do:

    | eval codes=replace(codes,"\"","")
    

    to pull the quote marks