将ps辅助转换为json

col17t5w  于 2023-02-14  发布在  其他
关注(0)|答案(5)|浏览(225)

我尝试不使用Perl或Python将ps aux的输出转换为Json格式!对于这些我读过jq。但是我成功地将命令行输出转换为json。
如何将简单的ps aux转换为Json?

mtb9vblg

mtb9vblg1#

ps aux | awk '
BEGIN { ORS = ""; print " [ "}
{ printf "%s{\"user\": \"%s\", \"pid\": \"%s\", \"cpu\": \"%s\"}",
      separator, $1, $2, $3
  separator = ", "
}
END { print " ] " }';

只需从ps辅助输出中调整您需要的列。

cs7cruho

cs7cruho2#

jq可以读取非JSON输入,您需要先用awk预处理输入:

ps aux |
  awk -v OFS=, '{print $1, $2}' | 
  jq -R 'split(",") | {user: .[0], pid: .[1]}'

如果您需要数组而不是对象序列,请通过jq --slurp 'add'传输输出(我发誓有一种方法可以做到这一点,而无需额外调用jq,但我现在想不起来了)。

lnlaulya

lnlaulya3#

下面是一个基于标记化的jq解决方案。
可以使用以下命令执行标记化:

def tokens:
  def trim: sub("^ +";"") |  sub(" +$";"");
  trim | splits(" +");

为了说明和简洁起见,我们只考虑前10个标记:

[tokens] | .[0:9]

调用:

$ ps aux | jq -c -R  -f tokens.jq

或者作为一行程序,您可以使用以下代码:

$  ps aux | jq -cR '[splits(" +")] | .[0:9]'

输出的前几行:

["USER","PID","%CPU","%MEM","VSZ","RSS","TT","STAT","STARTED"]
["p","1595","55.9","0.4","2593756","32832","??","R","24Jan17"]
["p","12472","26.6","12.6","4951848","1058864","??","R","Sat01AM"]
["p","13239","10.9","1.5","4073756","128324","??","R","Sun12AM"]
["p","12482","7.8","1.2","3876628","101736","??","R","Sat01AM"]
["p","32039","7.7","1.4","4786968","118424","??","R","12Feb17"]
["_windowserver","425","7.6","0.8","3445536","65052","??","Ss","24Jan17"]

使用标题作为对象键

参见例如www.example.comhttps://github.com/stedolan/jq/wiki/Cookbook#convert-a-csv-file-with-headers-to-json

kgsdhlau

kgsdhlau4#

我有一个gist可以将ps输出转换为json。它在幕后使用jq,所以你需要安装它。但是你不需要知道jq

suzh9iv8

suzh9iv85#

将-o标志指定的字段转储为PID对象数组:

ps ax -o "stat,euid,ruid,tty,tpgid,sess,pgrp,ppid,pid,wchan,sz,pcpu,command" \
    | jq -sRr ' sub("\n$";"") | split("\n") | ([.[0]|splits(" +")]) as $header | .[1:] | [.[] | [. as $x | range($header|length) | {"key": $header[.], "value": (if .==($header|length-1) then ([$x|splits(" +")][.:]|join(" ")|tojson|.[1:length-1]) else ([$x|splits(" +")][.]) end) } ] | from_entries]'

这将构建一个头字段数组,为每个输出对象Map一个{key,value}对象数组,然后使用内置的from_entries过滤器将这些对象聚合到输出中。

相关问题