如何在Bash中以单行打印JSON

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

how to print json from bash in single line

问题

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

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

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

  1. primer query

我得到的输出是:

  1. {
  2. "model": "test-model",
  3. "prompt": "primer query"
  4. }

我想要的是{"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

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

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

  1. primer query

and the output I get is this

  1. {
  2. &quot;model&quot;: &quot;test-model&quot;,
  3. &quot;prompt&quot;: &quot;primer query&quot;
  4. }

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 应该足够了。

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

  1. jq -nc \
  2. --arg model "$model_name" \
  3. --arg prompt "$name" \
  4. '{$model, $prompt}' \
  5. >> "$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?

  1. jq -nc \
  2. --arg model &quot;$model_name&quot; \
  3. --arg prompt &quot;$name&quot; \
  4. &#39;{$model, $prompt}&#39; \
  5. &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:

确定