Shell: Map all keys in a string format (json compatible)

Viewed 31

I have an object in a file like:

foo.txt

{
"methods" :
      {
        0 : "GET",
      },
}

I would like to convert to json with jq or some other shell converter. Specifically I want to turn each key into a string 0 -> "0". Keys can be numerical or alphanumerical.

Update

Any other tool is also acceptable. Anything that gets the job done. Preferably a shell tool.

1 Answers

With hjson (using Python), you could use the -j flag

  -j            Output as formatted JSON.

as follows:

hjson -j yourfile.txt
{
  "methods": {
    "0": "GET"
  }
}

Another way could be using the YAML processor mikefarah/yq (written in Go) and its -o flag

  -o, --output-format string          [yaml|y|json|j|props|p|xml|x] output format type. (default "yaml")

as follows

yq -o json yourfile.txt
{
  "methods": {
    "0": "GET"
  }
}

But yq also has a JSON converter @json as built-in function, if you'd want to further adjust the data on the fly:

yq '@json' yourfile.txt
{"methods":{"0":"GET"}}
Related