英文:
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="$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"
The file is a simple test.txt
with only 1 line
primer query
and the output I get is this
{
"model": "test-model",
"prompt": "primer query"
}
What I want is {"model": "test-model", "prompt": "primer query"}
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 "$model_name" \
--arg prompt "$name" \
'{$model, $prompt}' \
>> "$dest_file"
The option -c
produces compact output which means that everything will be in a single line.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论