jq read .txt file and write the values to json file

32,537

-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.

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:

{
  "scsRequestId": null,
  "includeMetadata": true,
  "includeHoldings": true,
  "country": [
    "NSC",
    "KZC",
    "KCC",
    "KZL",
    "NZG",
    "VRU",
    "ESM",
    "KZF",
    "SFU",
    "EWF",
    "KQY",
    "KQV"
  ],
  "region": [],
  "oclcSymbol": []
}
Share:
32,537
mjo
Author by

mjo

Updated on July 09, 2022

Comments

  • mjo
    mjo almost 2 years

    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.

    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:

    "NSC"
    "KZC"
    "KCC"
    "KZL"
    "NZG"
    "VRU"
    "ESM"
    "KZF"
    "SFU"
    "EWF"
    "KQY"
    "KQV"
    

    and my JSON looks like this:

    {
      "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.