4

I get invalid JSON from a script, e.g.

{
  name: "Leo",
  active: true
}

Is there a bash install-able tool I can use to pipe that output and turn it into valid JSON so can be processed by jq given jq doesn't support it ?

This question is similar to Convert invalid json into valid json except I need a command line utility and not some replace based php code.

Community
  • 1
  • 1
Leo Gallucci
  • 16,355
  • 12
  • 77
  • 110

3 Answers3

7

Hjson does this kind of thing really well.

$ hjson -j <<EOF
> {
>   name: "Leo",
>   active: true
> }
> EOF
{
  "name": "Leo",
  "active": true
}
Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
  • Exactly what I was looking for. I'll use the python version `pip3 install hjson && cli53 list | python -m hjson.tool -j` Thanks!!! – Leo Gallucci Nov 26 '15 at 13:09
3

The jq FAQ at https://github.com/stedolan/jq/wiki/FAQ#processing-not-quite-valid-json lists several tools (including hjson) for converting near-JSON to JSON. Some of them can be used as bash commands, e.g. https://www.npmjs.com/package/any-json, which is particularly versatile.

Incidentally, since jq allows JSON to be specified in a jq program in a flexible way (e.g. quotation marks around key names can be omitted and "#" comments can be added), you can use jq itself to convert many instances of not-quite JSON to JSON. Using your example, if the not-quite JSON text is in a file named input.nqj, then the invocation:

$ jq -n -f input.nqj

would produce:

{
  "name": "Leo",
  "active": true
}
peak
  • 105,803
  • 17
  • 152
  • 177
1

As I don't know how easy it is to deploy Hjson (from Steve Bennett's answer), here's a more lightweight alternative, using sed:

$ sed 's/\b\([^:"]*\)\b\s*:/"\1":/g' <<EOF
> {
>   name: "Leo",
>   active: true
> }
> EOF
{
  "name": "Leo",
  "active": true
}

Note that this is more specific to the example you've provided in the question: it will only fix missing quotation around keys. Also, it might be too aggressive about that, as, for example, integer keys would be quoted as well.

matz
  • 626
  • 6
  • 18