0

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

peak
  • 105,803
  • 17
  • 152
  • 177
Atomiklan
  • 5,164
  • 11
  • 40
  • 62

2 Answers2

2

Use generic object index syntax, e.g:

.["stat.taco"]
oguz ismail
  • 1
  • 16
  • 47
  • 69
0

If you use the generic object syntax, e.g. .["stat.taco"], then chaining is done either using pipes as usual, or without the dot, e.g.

.["stat.taco"]["inner.key"]

If your jq is sufficiently recent, then you can use the chained-dot notation by quoting the keys with special characters, e.g.

."stat.taco"."inner.key"

You can also mix-and-match except that expressions such as: .["stat.taco"].["inner.key"] are not (as of jq 1.6) supported.

peak
  • 105,803
  • 17
  • 152
  • 177