Search code examples
jsonkeyspecial-charactersjq

Issues with JSON format while using jq commandline processor


I am trying to use the jq command line JSON processor https://shapeshed.com/jq-json/ (which works great) to process a JSON file that seems to have been made using some poor choices.

Normally your id and value in the JSON file would not contain any periods such as:

{"id":"d9s7g9df7sd9","name":"Tacos"}

To get Tacos from the file you would do the following in bash:

echo $json | jq -r '.name'

This will give you Tacos (There may be some extra code missing from that example but you get the point.)

I have a JSON file that looks like this:

{"stat.blah":123,"stat.taco":495,"stat.yum... etc.

Notice how they decided to use a period in the identifying field associated with the value? This makes using jq very difficult because it associates the period as a separator to dig down into child values in the JSON. Sure, I could first load my file, replace all "." with "_" and that would fix the problem, but this seems like a really dumb and hackish solution. I have no way to change how the initial JSON file is generated. I just have to deal with it. Is there a way in bash I can do some special escape to make it ignore the period?

Thanks


Solution

  • Use generic object index syntax, e.g:

    .["stat.taco"]