Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert invalid json into valid one in bash [closed]

Tags:

json

bash

jq

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.

like image 304
Leo Gallucci Avatar asked Sep 01 '25 22:09

Leo Gallucci


2 Answers

Hjson does this kind of thing really well.

$ hjson -j <<EOF
> {
>   name: "Leo",
>   active: true
> }
> EOF
{
  "name": "Leo",
  "active": true
}
like image 89
Steve Bennett Avatar answered Sep 03 '25 14:09

Steve Bennett


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
}
like image 28
peak Avatar answered Sep 03 '25 13:09

peak