jq 读取 .txt 文件并将值写入 json 文件
jq read .txt file and write the values to json file
我想使用 jq
来解析包含国家代码列表的 .txt
文件,并将它们写入 JSON 对象中的值。
这是我目前的情况:
cat myfile.json |
jq -R -f test_id.txt 'select(.country == []).country = "test_id.txt"' > newfile.json
其中 .txt
文件如下所示:
"NSC"
"KZC"
"KCC"
"KZL"
"NZG"
"VRU"
"ESM"
"KZF"
"SFU"
"EWF"
"KQY"
"KQV"
我的 JSON 看起来像这样:
{
"scsRequestId": null,
"includeMetadata": true,
"includeHoldings": true,
"country": [],
"region": [],
"oclcSymbol": []
}
这是我遇到的错误:
jq: error: syntax error, unexpected QQSTRING_START, expecting $end (Unix shell quoting issues?) at <top-level>, line 2:
"KZC"
jq: 1 compile error
我希望国家代码列表进入国家数组。
-f
的参数是要从中读取过滤器到 运行 的文件。如果你想从文件中读取数据,那是 --slurpfile
的用法,而不是 -f
.
因此:
jq --slurpfile countries test_id.txt '.country=$countries' <myfile.json >newfile.json
当 运行 使用您提供的输入时,newfile.json
中的结果内容为:
{
"scsRequestId": null,
"includeMetadata": true,
"includeHoldings": true,
"country": [
"NSC",
"KZC",
"KCC",
"KZL",
"NZG",
"VRU",
"ESM",
"KZF",
"SFU",
"EWF",
"KQY",
"KQV"
],
"region": [],
"oclcSymbol": []
}
我想使用 jq
来解析包含国家代码列表的 .txt
文件,并将它们写入 JSON 对象中的值。
这是我目前的情况:
cat myfile.json |
jq -R -f test_id.txt 'select(.country == []).country = "test_id.txt"' > newfile.json
其中 .txt
文件如下所示:
"NSC"
"KZC"
"KCC"
"KZL"
"NZG"
"VRU"
"ESM"
"KZF"
"SFU"
"EWF"
"KQY"
"KQV"
我的 JSON 看起来像这样:
{
"scsRequestId": null,
"includeMetadata": true,
"includeHoldings": true,
"country": [],
"region": [],
"oclcSymbol": []
}
这是我遇到的错误:
jq: error: syntax error, unexpected QQSTRING_START, expecting $end (Unix shell quoting issues?) at <top-level>, line 2:
"KZC"
jq: 1 compile error
我希望国家代码列表进入国家数组。
-f
的参数是要从中读取过滤器到 运行 的文件。如果你想从文件中读取数据,那是 --slurpfile
的用法,而不是 -f
.
因此:
jq --slurpfile countries test_id.txt '.country=$countries' <myfile.json >newfile.json
当 运行 使用您提供的输入时,newfile.json
中的结果内容为:
{
"scsRequestId": null,
"includeMetadata": true,
"includeHoldings": true,
"country": [
"NSC",
"KZC",
"KCC",
"KZL",
"NZG",
"VRU",
"ESM",
"KZF",
"SFU",
"EWF",
"KQY",
"KQV"
],
"region": [],
"oclcSymbol": []
}