[英]How to create a json file with jq
Now I am trying to make a json file.现在我正在尝试制作一个 json 文件。 I found an example which is with jq.
我找到了一个 jq 的例子。
echo "$(jq -n '{Test1: $ARGS.named}' \
--arg one 'Apple' \
--arg two 'Banana')" >> config.json
I can get the result and save it into config.json我可以得到结果并将其保存到 config.json
{
"Test1": {
"one": "Apple",
"two": "Banana"
}
}
Now, how to make the following result and save it.现在,如何制作以下结果并保存它。
{
"Test1": {
"one": "Apple",
"two": "Banana"
},
"Test2": {
"one": "Kiwi",
"two": "Tomato"
}
}
Thanks谢谢
Create a JSON file:创建一个 JSON 文件:
$ jq -n --arg one 'Apple' --arg two 'Banana' \
'{Test1: $ARGS.named}' > config.json
View the JSON file:查看JSON文件:
$ cat config.json
{
"Test1": {
"one": "Apple",
"two": "Banana"
}
}
Create another JSON file based on the first one (using jq's .
for the input object, and +
to add (merge) two objects):基于第一个创建另一个 JSON 文件(使用 jq 的
.
输入 object,并使用+
添加(合并)两个对象):
$ jq --arg one 'Kiwi' --arg two 'Tomato' \
'. + {Test2: $ARGS.named}' config.json > config2.json
View that other JSON file:查看其他 JSON 文件:
$ cat config2.json
{
"Test1": {
"one": "Apple",
"two": "Banana"
},
"Test2": {
"one": "Kiwi",
"two": "Tomato"
}
}
Overwrite the first one with the second one:用第二个覆盖第一个:
$ mv config2.json config.json
Now the first one has the content of the second one:现在第一个有第二个的内容:
$ cat config.json
{
"Test1": {
"one": "Apple",
"two": "Banana"
},
"Test2": {
"one": "Kiwi",
"two": "Tomato"
}
}
Without creating a temporary file, assuming your shell is POSIX-based:在不创建临时文件的情况下,假设您的 shell 是基于 POSIX 的:
{
jq -cn --arg one 'Apple' --arg two 'Banana' '{Test1: $ARGS.named}'
jq -cn --arg one 'Kiwi' --arg two 'Tomato' '{Test2: $ARGS.named}'
} | jq -s add > output.json
Or或者
jq -n \
--argjson Test1 "$(jq -n --arg one 'Apple' --arg two 'Banana' '$ARGS.named')" \
--argjson Test2 "$(jq -n --arg one 'Kiwi' --arg two 'Tomato' '$ARGS.named')" \
'$ARGS.named' > output.json
If this is a prelude to a list of "TestN" objects, we'll get a bit more programmitic, here with bash syntax:如果这是“TestN”对象列表的前奏,我们会得到更多的编程,这里使用 bash 语法:
ones=( Apple Kiwi )
twos=( Banana Tomato )
for ((i=0; i < ${#ones[@]}; i++)); do
jq -cn \
--arg one "${ones[i]}" \
--arg two "${twos[i]}" \
--arg key "Test$((i + 1))" \
'{($key): {$one, $two}}'
done | jq -s add > output.json
Or, use a different tool: jo或者,使用不同的工具: jo
jo Test1="$(jo one=Apple two=Banana)" Test2="$(jo one=Kiwi two=Tomato)"
{"Test1":{"one":"Apple","two":"Banana"},"Test2":{"one":"Kiwi","two":"Tomato"}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.