Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting JSON variable using bash

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

like image 456
Count Zero Avatar asked Sep 06 '25 01:09

Count Zero


2 Answers

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

  • http://kmkeen.com/jshon/
  • https://github.com/dominictarr/JSON.sh
like image 181
Dennis Avatar answered Sep 09 '25 03:09

Dennis


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)
like image 39
tworec Avatar answered Sep 09 '25 03:09

tworec