4

Possible Duplicate:
Parsing json with sed and awk

I have a JSON string like the example below and I want to use, for example, the value of the "uptime" command as a variable in a shell script, what should I do?

{ "serverStatus" : { "version" : "1.6.0", "uptime" : 527, "uptimeEstimate" : 526, "localTime" : { "$date" : 1286923624579 }, "globalLock" : { "totalTime" : 526604302, "lockTime" : 3499842, "ratio" : 0.006646056605895331, "currentQueue" : { "total" : 0, "readers" : 0, "writers" : 0 } }, "mem" : { "bits" : 64, "resident" : 150, "virtual" : 76114, "supported" : true, "mapped" : 75950 }, "connections" : { "current" : 1, "available" : 9599 }, "extra_info" : { "note" : "fields vary by platform", "heap_usage_bytes" : 600592, "page_faults" : 1838 }, "indexCounters"....

2
  • Given the lack of a bash, csh, zsh, tcsh, etc library listed at json.org — write a library and contribute it? Commented Oct 12, 2010 at 23:13
  • 2
    @Josh: All your edit are belong to us. Commented Oct 12, 2010 at 23:17

2 Answers 2

6

You can use a programming language with a json module, or if you desire a shell+*nix tool solution, you can use awk

$ awk -F"[,:]" '{for(i=1;i<=NF;i++){if($i~/uptime\042/){print $(i+1)} } }' file
 527
Sign up to request clarification or add additional context in comments.

2 Comments

Works ok for the uptime value in his example json. But won't work for values like html code.
Correct me if I am wrong, The one shown in your example is for substring comparison .What condition should be used in if loop to check if $i is equal to uptime.?
1

Version which uses ruby:

cat file | ruby -e "require 'rubygems'; require 'json'; puts JSON[STDIN.read]['serverStatus']['uptime'];"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.