A
A
Anton2019-02-26 15:56:39
Python
Anton, 2019-02-26 15:56:39

What is the correct way to convert bash output to JSON with {#PROCNAME} key?

I'm trying to get JSON from the top 5 processes from memory.
I want to send this JSON to Zabbix and draw the top 5 processes from memory.
I get the top 5 processes by memory with the command:

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

How to convert bash output to JSON with key {#PROCNAME} to get structure like this:
{
  "data": [
    {
      "{#PROCNAME}": "node"
    },
    {
      "{#PROCNAME}": "mongod"
    },
    {
      "{#PROCNAME}": "kubelet"
    },
    {
      "{#PROCNAME}": "dockerd"
    },
    {
      "{#PROCNAME}": "systemd-journal"
    }
  ]
}

Using jq or python. Does anyone have any ideas on how to roughly do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton, 2019-02-26
Patsev @chemtech

ps axho comm --sort -rss | head -5 | jq -Rn '{data: [inputs|{"{#PROCNAME}":.}]}' 
{
  "data": [
    {
      "{#PROCNAME}": "node"
    },
    {
      "{#PROCNAME}": "mongod"
    },
    {
      "{#PROCNAME}": "kubelet"
    },
    {
      "{#PROCNAME}": "dockerd"
    },
    {
      "{#PROCNAME}": "systemd-journal"
    }
  ]
}

Q
q2zoff, 2019-02-26
@q27off

echo -e '{\n\t"data": ['

ps axho comm --sort -rss | head -5 |
while read -r proc
do
    echo -ne '\t\t{\n\t\t\t"{#PROCNAME}":'
    echo " \"$proc\""
    echo -e '\t\t},'
done

echo -e '\t]\n}'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question