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
  • 172
  • 3
  • 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
  • 35,528
  • 7
  • 73
  • 70