I have a splunk query which generates output in csv/table format. I wanted to convert this to a json format before writing it into a file. tojson does the job of converting. However the fileds are not in the order I expect it to be. Table output:
timestamp,Subject,emailBody,operation --> resulting JSON output is in the order subject,emailbody,operation,timestamp. How do I manipulate tojson to write fields in this order or is there an alternate way of getting json output as expected?
Json is a structured format so the order of fields should not matter for the recipient. After all you will be addressing the fields by their names. Unless you're manipulating that json on the receiving end using something not fit for json processing. In that case maybe json is not the best format choice.
JSON is a structure that does not require any specific order of key. If your downstream application has this requirement, they are noncompliant to the standard. You don't have to make any change. Demand that your downstream developer make change.
Json is a structured format so the order of fields should not matter for the recipient. After all you will be addressing the fields by their names. Unless you're manipulating that json on the receiving end using something not fit for json processing. In that case maybe json is not the best format choice.
I had same understanding, thanks for confirming that. I am asked to modify the raw event that we receive in JSON format to include new key value pair and to replace the value of one of the field value for a specific key.
Wait a second. Firstly you've been asking about "sorting" json fields on output of the search (at least that's how I understood your question). Now you're saying you want to modify _raw event. By "modifying" I understand that you want to do it before the event is written to an index. Manipulating structured data with just regexes is not a very good idea (maybe except for very easy cases but even then I'd be very careful).
Agreed. I will mark this as closed and raise a new question for what am trying to do. Thanks for your help
I think it is not possible to change the order of the fields with tojson command.
But try to create a json object with eval and json_object function maybe that accomplish your goal.
...your search...
|eval my_json_object=("timestamp",timestamp,"Subject",Subject,"emailBody",emailBody,"operation",operation)
This was my last fall back option as I have multiple fields and the query would become lengthy. This also gives me the flexibility to add extra fields to the _raw event. I am just assuming that splunk has some inbuilt solution that I might be missing