Search code examples
jsonjqmongoimportjtc

how to find/replace in a json file using jtc?


I have the file below. Using jtc how to I replace all occurrences of "value": 1234.56 with "value": {"$numberDecimal":"1234.56"}; that is, wrap the numbers. This is for mongoimport, I want to require values to be imported as decimals not floats.

Or maybe there's a better solution using jq?

An example file:

{
  "data": {
    "slice": [
      {
        "source": {
          "id": "foo"
        },
        "value": 1.0
      },
      {
        "source": {
          "id": "bar"
        },
        "value": 2.0
      }
    ]
  }
}

Solution

  • If I understand the question correctly, then with the latest jtc build you can do it like this:

    bash $ <file.json jtc -w'[value]:<>N:' -u'{"$numberDecimal":"{}"};' -tc
    {
       "data": {
          "slice": [
             {
                "source": { "id": "foo" },
                "value": { "$numberDecimal": "1.0" }
             },
             {
                "source": { "id": "bar" },
                "value": { "$numberDecimal": "2.0" }
             }
          ]
       }
    }
    bash $ 
    

    and if you like to do an in-place file modifications then use -f:

    bash $ jtc -w'[value]:<>N:' -u'{"$numberDecimal":"{}"};' -f file.json