将ps aux转换为json

时间:2017-03-17 10:48:16

标签: json linux jq

我尝试将GET的输出转换为Json格式而不使用Perl或Python!对于这些我读过有关jq的内容。但我已成功将命令行输出转换为json。

如何将simpe ps aux转换为Json?

4 个答案:

答案 0 :(得分:1)

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

只需从ps aux输出中调整所需的列。

答案 1 :(得分:0)

jq可以读取非JSON输入。您希望首先使用awk预处理输入:

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

如果您想要一个数组而不是一系列对象,请通过jq --slurp 'add'管道输出。 (我发誓在没有额外打电话给jq的情况下做到这一点,但此刻它逃脱了我。)

答案 2 :(得分:0)

这是基于标记化的唯一-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"]

使用标题作为对象键

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

答案 3 :(得分:0)

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