Search code examples
pythonjsonzabbix

Create JSON using python with sequence key for LLD Zabbix discovery top mem process


I try create JSON using python with sequence key for LLD Zabbix discovery top mem process

#!/usr/bin/python

import subprocess
import json

s = subprocess.Popen(["ps axho comm --sort -rss | head -5"], shell=True, stdout=subprocess.PIPE).stdout
service_states = s.read().splitlines()

count = 0
data = {"data":{}}
for i in service_states:
  count += 1
  key = "{#TOPMEMNAME" + str(count) + "}"
  data["data"][key] = i

json_data = json.dumps(data)
print(json_data)

Get JSON not accepted Zabbix (Below code):

{
  "data": {
    "{#TOPMEMNAME2}": "node",
    "{#TOPMEMNAME1}": "mongod",
    "{#TOPMEMNAME4}": "ffmpeg",
    "{#TOPMEMNAME3}": "kubelet",
    "{#TOPMEMNAME5}": "dockerd"
  }
}

Below code where Zabbix accepted JSON.

{
    "data": [{
            "{#TOPMEMNAME1}": "mongod"
        },
        {
            "{#TOPMEMNAME2}": "node"
        },
        {
            "{#TOPMEMNAME3}": "kubelet"
        },
        {
            "{#TOPMEMNAME4}": "ffmpeg"
        },
        {
            "{#TOPMEMNAME5}": "dockerd"
        }
    ]
}

How change python code for get JSON zabbix accepted ?


Solution

  • data = {"data":{}}
    # should be changed to the line below
    data = {"data":[]}
    
    data["data"][key] = i
    # should be changed to the line below
    data["data"].append({key:i})