[英]jq add file contents into json and update
I'm trying to use take a JSON object from a REST API GET
call, then add the contents of a raw file (.md file in this case) into it using jq , before updating the same object using a PUT
call. 我正在尝试使用REST API GET
调用中的JSON对象,然后使用jq将原始文件(在本例中为.md文件)的内容添加到其中,然后使用PUT
调用更新同一对象。
I'm using the following to GET the file and write it locally: 我正在使用以下内容获取文件并在本地编写它:
curl -u USERNAME:PASSWORD 'https://example.com/myfile.json' | cat > ./test.json
The format of the JSON file is as follows: JSON文件的格式如下:
{
"content" : "My JSON content",
"owner":...
}
I'd like to add the content of the raw file into content
, so the result is as follows: 我想将原始文件的内容添加到content
,结果如下:
{
"content" : "My markdown file contents.\n\nMy JSON content",
"owner":...
}
and then update the original JSON using a PUT
call: 然后使用PUT
调用更新原始JSON:
curl -u USERNAME:PASSWORD -d @./test.json -H "Content-Type: application/json" -X PUT 'https://example.com/myfile.json'
I'm wondering how I can add the file content into my JSON
file like that using jq , if it is possible? 我想知道如何将文件内容添加到我的JSON
文件中,就像使用jq一样 ,如果可能的话?
The key to a simple jq solution here is to read the raw text file using 'jq -R -s', and to read the JSON using one of the options in the --arg family. 这里简单的jq解决方案的关键是使用'jq -R -s'读取原始文本文件,并使用--arg系列中的一个选项读取JSON。 Here, I'll use --argfile
for simplicity and robustness across jq versions, but please note that the documentation says it is deprecated. 在这里,我将使用--argfile
来实现jq版本的简单性和健壮性,但请注意文档说它已被弃用。
With the following jq program in a file, say program.jq: 使用文件中的以下jq程序,例如program.jq:
. as $file
| $json
| (.content = $file + "\n" + .content)
and the following text in the file contents.txt
: 以及文件contents.txt
的以下文本:
Line 1 of contents.txt;
line 2.
and the following JSON in curl.json: 以及curl.json中的以下JSON:
{
"content": "My JSON content",
"owner": "etc"
}
the invocation: 调用:
jq -R -s --argfile json curl.json -f program.jq contents.txt
produces: 生产:
{
"content": "Line 1 of contents.txt;\nline 2.\n\nMy JSON content",
"owner": "etc"
}
If using bash, instead of putting the curl output into a file, you could use: --argfile json <(curl ....) 如果使用bash,而不是将curl输出放入文件中,您可以使用: - argfile json <(curl ....)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.