bash jq 读取 .txt 文件并将值写入 json 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36273218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jq read .txt file and write the values to json file
提问by mjo
I want to use jq
to parse a .txt
file with a list of country codes and write them to the value in a JSON object.
我想用来jq
解析.txt
带有国家代码列表的文件,并将它们写入 JSON 对象中的值。
Here is what I have so far:
这是我到目前为止所拥有的:
cat myfile.json |
jq -R -f test_id.txt 'select(.country == []).country = "test_id.txt"' > newfile.json
Where .txt
file looks like this:
其中.txt
文件如下所示:
"NSC"
"KZC"
"KCC"
"KZL"
"NZG"
"VRU"
"ESM"
"KZF"
"SFU"
"EWF"
"KQY"
"KQV"
and my JSON looks like this:
我的 JSON 如下所示:
{
"scsRequestId": null,
"includeMetadata": true,
"includeHoldings": true,
"country": [],
"region": [],
"oclcSymbol": []
}
Here is the error I am getting:
这是我得到的错误:
jq: error: syntax error, unexpected QQSTRING_START, expecting $end (Unix shell quoting issues?) at <top-level>, line 2:
"KZC"
jq: 1 compile error
I want the list of country codes to go into the country array.
我希望国家代码列表进入国家数组。
回答by Charles Duffy
-f
's argument is the file to read the filter to run from. If you want to read data from a file, that's a use for --slurpfile
, not -f
.
-f
的参数是读取过滤器运行的文件。如果你想从文件中读取数据,那是用于--slurpfile
,而不是-f
。
Thus:
因此:
jq --slurpfile countries test_id.txt '.country=$countries' <myfile.json >newfile.json
When run with your provided inputs, the resulting contents in newfile.json
are:
使用您提供的输入运行时,结果内容newfile.json
为:
{
"scsRequestId": null,
"includeMetadata": true,
"includeHoldings": true,
"country": [
"NSC",
"KZC",
"KCC",
"KZL",
"NZG",
"VRU",
"ESM",
"KZF",
"SFU",
"EWF",
"KQY",
"KQV"
],
"region": [],
"oclcSymbol": []
}