jq转换文本字符串并将它们添加到现有的json对象中

时间:2017-05-24 05:34:51

标签: json bash sh text-processing jq

如何转换文本字符串并将其添加到现有的json对象

当前的json输出:

{
  "start process": "Wed May 24 05:22:35 UTC 2017",
  "logfilename": "log_test"
}
{
  "start filelist": [
    "/downloads/json_log_array2object.jq",
    "/downloads/json_log_string2object.jq",
    "/downloads/log_test.json",
    "/downloads/log_test.txt",
    "/downloads/test_logs.sh"
  ]
}

目标json输出:

{
  "start process": "Wed May 24 05:22:35 UTC 2017",
  "logfilename": "log_test",
  "start filelist": [
    "/downloads/json_log_array2object.jq",
    "/downloads/json_log_string2object.jq",
    "/downloads/log_test.json",
    "/downloads/log_test.txt",
    "/downloads/test_logs.sh"
  ]
}

bash脚本:

logfilename="log_test"

writelogstring2object() {
  exec 4>>"${1}.json"
  flock -x 4
  tee -a "$1.txt" | jq -sRf json_log_string2object.jq >&4
}

writelogarray2object() {
  exec 4>>"${1}.json"
  flock -x 4
  tee -a "$1.txt" | jq -nRf json_log_array2object.jq >&4
}

exec 3> >(writelogstring2object "$logfilename")
{
echo "start process: $(date -u)"
echo "logfilename:" $logfilename
} >&3
exec 3>&-
flock -s "$logfilename.json" -c :

exec 3> >(writelogarray2object "$logfilename")
{
echo "start filelist:"
printf '%s\n' "$PWD"/*
} >&3
exec 3>&-
flock -s "$logfilename.json" -c :

jq程序:

json_log_string2object.jq

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

def s2o:
  (index(":") // empty) as $ix
  | {(.[:$ix]): (.[$ix+1:]|trim)};

split("\n") | map(s2o) | add

json_log_array2object.jq

foreach (inputs,null) as $line ({};
   if $line == null then .emit = {(.key|tostring): .value}
   elif $line[-1:] == ":"
   then (if .key then {emit: {(.key): .value}} else null end)
        + { key : $line[0:-1] }
   else {key, value: (.value + [$line])}
   end;
   .emit // empty )

欣赏方法和例子

1 个答案:

答案 0 :(得分:1)

  1. 要添加两个JSON对象,$ 1和$ 2,您可以编写$one + $two

  2. 在问题描述开头给出的两个对象作为JSON不是很有效。假设文件input.json包含更正的文本,则调用:

    jq -s'。[0] +。[1]' input.json

  3. 产生了理想的答案。