2

I'm trying to get a JSON document with the top 5 processes by memory.

This JSON I want to send to Zabbix and draw the top 5 processes by memory.

I get the top 5 processes by memory by the following command:

ps axho comm --sort -rss | head -5
node
mongod
kubelet
dockerd
systemd-journal

How to convert the output of ps+head to JSON with key {#PROCNAME} to get this structure:

{
  "data": [
    {
      "{#PROCNAME}": "node"
    },
    {
      "{#PROCNAME}": "mongod"
    },
    {
      "{#PROCNAME}": "kubelet"
    },
    {
      "{#PROCNAME}": "dockerd"
    },
    {
      "{#PROCNAME}": "systemd-journal"
    }
  ]
}

https://www.zabbix.com/documentation/current/manual/config/macros/lld_macros

There is a type of macro used within the low-level discovery (LLD) function:

{#MACRO} 
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Anton Patsev
  • 135
  • 1
  • 8

3 Answers3

8

If your jq has the inputs function, and assuming {#PROCNAME} is just a string, you can use the following:

ps axho comm --sort -rss | head -5 | jq -Rn '{data: [inputs|{"#PROCNAME":.}]}'

The inputs functions lets jq read all input string. The rest is decoration to get the wanted format.

The option -R gets raw string as input. The option -n feeds jq input with null entry. That way inputs gets all strings at once.

oliv
  • 2,586
  • 9
  • 14
1

actually, you could achieve it with just standard unix cli:

bash $ echo { \"data\": [  $(ps axho comm --sort -rss | head -5 | xargs -L1 -I% echo { \"{#PROCNAME}\": \"%\" } | paste -s -d, -) ] }
{ "data": [ { "{#PROCNAME}": "node" },{ "{#PROCNAME}": "mongod" },{ "{#PROCNAME}": "kubelet" },{ "{#PROCNAME}": "dockerd" },{ "{#PROCNAME}": "systemd-journal" } ] }
bash $ 
  • the resulting output is a valid JSON.
Dmitry
  • 11
  • 1
0

This is similar to oliv's solution, but moves the head operation into jq:

ps axho comm --sort -rss |
jq -Rn '[inputs][:5] | { data: map({ "{#PROCNAME}": . }) }'

The first part, [inputs][:5], extracts the five first lines from the output of ps as an array, and the second part inserts this array as the value of data, with each of its elements converted into a separate object with a {#PROCNAME} key.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936