jq读取.txt文件并将值写入json文件

时间:2016-03-29 00:00:11

标签: json bash jq

我想使用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`

我希望国家/地区代码列表进入国家/地区数组。

感谢任何帮助

1 个答案:

答案 0 :(得分:8)

-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": []
}