4

I need to extract the variable from a JSON encoded file and assign it to a variable in Bash.

excerpt...from file.json

  "VariableA": "VariableA data", 
    "VariableB": [
        "VariableB1", 
        "VariableB2", 
        "VariableB3", 
        "VariableB3"
    ], 

I've gotten somewhere with this

variableA=$(fgrep -m 1 "VariableA" file.json )

but it returns the whole line. I just want the data

For the VariableB I need to replace the list with comma separated values.

I've looked at awk, sed, grep, regexpressions and really given the learning curve...need to know which one to use, or a better solution.

Thanks for your suggestions...but this is perfect git://github.com/kristopolous/TickTick.git

3 Answers 3

7

You are better off using a JSON parser. There are many listed at http://json.org/ including two for the BASH shell.

Sign up to request clarification or add additional context in comments.

1 Comment

jsawk worked for me. And it was fairly easy to install on OS X.
4

There is powerful command-line JSON tool jq.

Extracting single value is easy:

variableA=$(jq .VariableA file.json)

For comma separated array contents try this

variableB=$(jq '.VariableB | @csv' file.json)

or

variableB=$(jq '.VariableB | .[]' file.json | tr '\n' ',' | head -c-1)

Comments

0

If you're open to using Perl they have a 'open()' function that will pipe a file with the json function 'to_json'. And if you want to extract json you can use the 'from_json' function. You can check it out here:

http://search.cpan.org/~rjbs/perl-5.16.0/lib/open.pm

http://metacpan.org/pod/JSON#to_json

http://metacpan.org/pod/JSON#from_json ( you might also try using decode json as well)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.