如何在Bash中以单行打印JSON

huangapple go评论78阅读模式
英文:

how to print json from bash in single line

问题

我必须从文本文件中生成一个JSON字符串,但输出结果会跨多行。
我的代码:

#!/usr/bin/bash
filename="$1"
dest_file=output/output.jsonl
while read -r line; do
    name="$line"
    echo "Name read from file - $name"
    model_name="test-model"
    JSON_STRING=$(jq -n --arg model "$model_name" --arg prompt "$name" '{model: $model, prompt: $prompt}')
    printf "%s" "$JSON_STRING" >> "$dest_file"
done < "$filename"

文件是一个简单的test.txt,只有1行:

primer query

我得到的输出是:

{
  "model": "test-model",
  "prompt": "primer query"
}

我想要的是{"model": "test-model", "prompt": "primer query"}在一行中。我尝试过jq -c但它会给出空的输出。

英文:

I have to derive a json String from a text file but the output happens to go into multiple lines.
My code

#!/usr/bin/bash
filename=&quot;$1&quot;
dest_file= output/output.jsonl
while read -r line; do
    name=&quot;$line&quot;
    echo &quot;Name read from file - $name&quot;
    model_name=&quot;test-model&quot;
    JSON_STRING=$(  jq -n  --arg model &quot;$model_name&quot; --arg prompt &quot;$name&quot; &#39;{model: $model, prompt: $prompt}&#39; )
    printf &quot;%s&quot; &quot;$JSON_STRING&quot; &gt;&gt; &quot;$dest_file&quot;
done &lt; &quot;$filename&quot;

The file is a simple test.txt
with only 1 line

 primer query

and the output I get is this

{
  &quot;model&quot;: &quot;test-model&quot;,
  &quot;prompt&quot;: &quot;primer query&quot;
}

What I want is {&quot;model&quot;: &quot;test-model&quot;, &quot;prompt&quot;: &quot;primer query&quot;} in one line
I tried jq -c but then it gives empty output

答案1

得分: 1

这看起来很复杂,绝对不需要使用 bash,简单的 sh 应该足够了。

为什么要将命令的输出存储在一个变量中,然后打印、格式化和重定向变量的内容?

jq -nc \
  --arg model "$model_name" \
  --arg prompt "$name" \
  '{$model, $prompt}' \
  >> "$dest_file"

选项 -c 生成 紧凑输出,这意味着所有内容都将在一行中。

英文:

This looks complicated and definitely doesn't require bash, the simple sh should suffice here.

Why store the output of the command in a variable and then print and format + redirect the content of the variable?

jq -nc \
  --arg model &quot;$model_name&quot; \
  --arg prompt &quot;$name&quot; \
  &#39;{$model, $prompt}&#39; \
  &gt;&gt; &quot;$dest_file&quot;

The option -c produces compact output which means that everything will be in a single line.

huangapple
  • 本文由 发表于 2023年7月18日 09:22:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定