Bash脚本以json格式打印输出

时间:2016-09-03 15:22:56

标签: linux bash shell awk sed

我试图卷曲网页并对其进行一些处理,最后我尝试以json格式打印。(实际上需要在mongodb输入中)

所以输入(通过卷曲读取)是

输入:

brendan google engineer
stones microsoft chief_engineer
david facebook tester

对于处理类型,我为变量赋值($ name,$ emloyer,$ designation)

我转换为json的最终命令是,

echo [{\"Name\":\"$name\"},{\"Employer\":\"$employer\"},{\"dDesignation\":\"$designation\"}]

当前输出为

[{"Name":"brendan","Employer":"google","Designation":"engineer"}]
[{"Name":"stones","Employer":"microsoft","Designation":"chief_engineer"}]
[{"Name":"david","Employer":"facebook","Designation":"tester"}]

但是,我希望同一行中的输出在开头和结尾用逗号和方括号分隔(不是在每一行)

预期输出:

  [{"Name":"brendan","Employer":"google","Designation":"engineer"},{"Name":"stones","Employer":"microsoft","Designation":"chief_engineer"},
    {"Name":"david","Employer":"facebook","Designation":"tester"}]

任何建议。

3 个答案:

答案 0 :(得分:7)

传统的文本处理工具无法针对一般情况执行此操作。 JSON有很多极端案例 - 例如,需要转义非打印和高Unicode字符(和引号)。使用实际为作业构建的工具,例如jq

jq -n -R '
[
  inputs |
  split(" ") |
  { "Name": .[0], "Employer": .[1], "Designation": .[2] }
]' <<EOF
brendan google engineer
stones microsoft chief_engineer
david facebook tester
EOF

...作为输出发出:

[
  {
    "Name": "brendan",
    "Employer": "google",
    "Designation": "engineer"
  },
  {
    "Name": "stones",
    "Employer": "microsoft",
    "Designation": "chief_engineer"
  },
  {
    "Name": "david",
    "Employer": "facebook",
    "Designation": "tester"
  }
]

答案 1 :(得分:1)

这样的东西?

sep='['
curl "...whatever..." |
while read -r name employer designation; do
    printf '%s{"Name": "%s", "Employer": "%s", "Designation": "%s"}' "$sep" "$name" "$employer" "$designation"
    sep=', '
done
printf ']\n'

我确实认为这很脆弱且容易出错;如果您可以使用像jq这样的JSON感知工具,请务必这样做。

答案 2 :(得分:0)

如果您有权访问jq 1.5或更高版本,那么您可以使用inputs,并且如果令牌可能被多个空格分隔,可能会考虑使用splits(" +")

jq -n -R '
  [inputs
   | [splits(" +")]
   | { "Name": .[0], "Employer": .[1], "Designation": .[2] }]'

如果您没有准备好访问jq 1.5或更高版本,请注意以下内容适用于jq 1.4:

jq -R -s '
  [split("\n")[]
   | select(length>0)
   | split(" ")
   | { "Name": .[0], "Employer": .[1], "Designation": .[2] }]'