0

Bash parse json file. I need to get the version value from a json file shich looks like this :

{
 "attributes": {
 },
  "groupings": {
 },
 "recipes": {
 },
 "version": "0.2.54",
"source_url": "",
"issues_url": "" 
}

But on other servers it look like this (without spaces)

 "attributes": {},"groupings": {},"recipes":{},"version": "0.2.54","source_url": "","issues_url": ""}

I tried solving this with "grep -Po" but wouldn't work on the jsons without spaces and than trying to solve this with sed&awk but wouldn't work on jsons with spaces. Is there another way to do this noting that I'm trying to use this in a script and connecting to servers with "knife ssh"

Vlad Cenan
  • 160
  • 1
  • 11
  • I suggest to use `jq` for this job. – Cyrus Sep 11 '16 at 09:44
  • I saw but it's more complicated facing the fact that I'm connecting on each server from an environment and I have to install the tool on each server. Ans\d also update the centos repo because I wasn't able to install it simply with "yum install jq" – Vlad Cenan Sep 11 '16 at 09:46
  • With your example: `tr -cd '[0-9].' < file` ;) – Cyrus Sep 11 '16 at 09:58
  • With a suitable regex, `grep -Po` should work fine, with the usual caveats. You're not showing your attempt so we can't help you figure out why it failed. – tripleee Sep 11 '16 at 11:58
  • yes tr -cd would work in this example but obviously metadata is bigger and it brought a lot's of 0.0.0....Nice trick anyway. – Vlad Cenan Sep 11 '16 at 13:11
  • I chose this 'grep -ri 'version' /var/chef/cache/cookbooks/service/metadata.json' | awk '{print $3}' | tr -cd '[0-9].' – Vlad Cenan Sep 11 '16 at 13:57

1 Answers1

1

Use jq, to install use the following:

apt-get install jq

Usage:

jq .version <filename>
"0.2.54"

Please note that I copied your entire jason to a file named test. that means I added missing { in the following:

{"attributes": {},"groupings": {},"recipes":{},"version": "0.2.54","source_url": "","issues_url": ""}
Farhad Farahi
  • 30,830
  • 7
  • 71
  • 65
  • That's a [useless use of `cat`](http://www.iki.fi/era/unix/award.html). Just like pretty much any other well-behaved filter program (except `tr`!), `jq` accepts an optional list of input file name arguments. – tripleee Sep 11 '16 at 12:01
  • Yes it will work on dev and test environments but I can't install extra tools in production. apt-get willwork for Ubuntu/Debia platforms. My scenarios is with Centos 6.5/6.7 an aparantly Centos repos can't find jq. – Vlad Cenan Sep 11 '16 at 12:46