Splunk Search

How to extract elements of a json (not a json array)

weidertc
Contributor

I have a json from Grafana.

| makeresults count=1
| eval json = "{
  \"datasources\": {
    \"ds_a\": {},
    \"ds_b\": {},
    \"ds_c\": {}
  }
}"
| eval json_valid = if(json_valid(json), "Valid", "Invlaid")
| spath input=json path=datasources{} output=datasources

 

the only other relative piece of information not shown above is some values within the inner braces themselves contain braces, so using a regex unfortunately hasn't worked.

I need to extract the elements of "dataSources", but the | spath is not working.

I need a multivalue field like this

\"ds_a\": {}
\"ds_b\": {}
\"ds_c\": {}

 

How can i do this when dataSources is not a [] ?

 

Labels (1)
0 Karma

PickleRick
SplunkTrust
SplunkTrust

You want a multivalued field with each field being a "crippled json"?

You could use json_keys() and then do some sort of foreach-based eval.

0 Karma

ITWhisperer
SplunkTrust
SplunkTrust
| makeresults count=1
| eval json = "{
  \"datasources\": {
    \"ds_a\": {},
    \"ds_b\": {},
    \"ds_c\": {}
  }
}"
| eval json_valid = if(json_valid(json), "Valid", "Invlaid")
| eval keys = json_keys(json)
| eval datasources = json_extract(json,json_array_to_mv(keys))
| eval datasources_keys = json_keys(datasources)
| eval mv_keys=json_array_to_mv(datasources_keys)
| foreach mode=multivalue mv_keys
    [| eval array=if(isnull(array),"\"".<<ITEM>>."\": ".json_extract(datasources,<<ITEM>>),mvappend(array,"\"".<<ITEM>>."\": ".json_extract(datasources,<<ITEM>>)))]
0 Karma

yuanliu
SplunkTrust
SplunkTrust

This can be further simplified using the json_array mode of foreach.

| makeresults count=1
| eval json = "{
  \"datasources\": {
    \"ds_a\": {},
    \"ds_b\": {},
    \"ds_c\": {}
  }
}"
| spath input=json path=datasources

| eval key = json_keys(datasources)
| foreach key mode=json_array
    [ eval object = mvappend(object, '<<ITEM>>' . ":" . spath(datasources, <<ITEM>>)) ]
0 Karma
Career Survey
First 500 qualified respondents will receive a $20 gift card! Tell us about your professional Splunk journey.
Get Updates on the Splunk Community!

Tech Talk Recap | Mastering Threat Hunting

Mastering Threat HuntingDive into the world of threat hunting, exploring the key differences between ...

Observability for AI Applications: Troubleshooting Latency

If you’re working with proprietary company data, you’re probably going to have a locally hosted LLM or many ...

Splunk AI Assistant for SPL vs. ChatGPT: Which One is Better?

In the age of AI, every tool promises to make our lives easier. From summarizing content to writing code, ...