bashshelljq

JQ issues with comments on Json file


I'm using JQ https://stedolan.github.io/jq/ to work in bash with my json and when I read the json is throwing me an error

   parse error: Invalid numeric literal at line 2, column 5=

Since my json has some comments

  // comment
  "spawn": {}

I've been seen looking the options and I cannot find any option to fix the problem. Any idea how to solve it?


Solution

  • JSON and thus jq do not support comments (in the usual sense) in JSON input. The jq FAQ lists a number of tools that can be used to remove comments, including jsonlint, json5, and any-json. I'd recommend one that can act as a filter.

    For NDJSON with #-style comments on separate lines, you could use jq by filtering out the #-style comments as follows:

    jq -Rcn '
      def iterate(f): def r: f | (., r); r;
      iterate(try (inputs|fromjson) catch infinite)
      | select(isinfinite|not)'
    

    (This also works with gojq and jaq, the Go and Rust implementation of jq.)

    See https://github.com/stedolan/jq/wiki/FAQ#processing-not-quite-valid-json for links and further details.
    ā€”ā€”

    It might be worth pointing out that jq can be used to process JSON with #-style comments, at least if the JSON is not too large to be processed as a jq program. For example, you could use jq with the -f option to read a JSON file as a jq program.