1

I'm using bash script that needs to read the JSON output and parse a value from different JSON variables or strings. Here's the sample output. It needs to read the value next to the Content or from any other variable. Such as,

Lookup Content and be able to print Value1.

Lookup DeviceType and be able to print Value4

Sample Ouput: {"Content":"Value1","CreationMethod":"Value2","database":"Value3","DeviceType":"Value4"}

I tried the combination of sed and awk sed 's/["]/ /g' | awk '{print $4}', but only if the position of Content remains the same in the output. otherwise in the different JSON output, the positioning of Content changes that puts the value out of scope thus awk '{print $4}' picks up the wrong value.

9
  • 3
    "No jq" - no good JSON parsing Nov 8, 2019 at 15:55
  • 4
    This would be trivial with jq, or any other JSON parser. With sed and or awk, you would not only have to rely on the document always being formatted exactly the same way, but also do your own string decoding in case the data is JSON encoded.
    – Kusalananda
    Nov 8, 2019 at 15:56
  • 1
    Is using bash a mandatory requirement?
    – schaiba
    Nov 8, 2019 at 15:56
  • 1
    Is Perl allowed?
    – choroba
    Nov 8, 2019 at 16:05
  • 3
    How about Python? Any scripting language? What is the reason for ruling out the most suitable tools for the job?
    – JigglyNaga
    Nov 8, 2019 at 17:12

4 Answers 4

1

Well, if I understand you correctly, with GNU grep and tr:

tr ',' '\n' < foo | grep -Po "(?<=Content\":\").*(?=\")"

Output:

Value1

With other keyword:

tr ',' '\n' < foo | grep -Po "(?<=database\":\").*(?=\")"

Value 3

Replace the commas for a new line:

tr ',' '\n'

Grep -o only -P perl like regex

grep -Po

Catch the pattern ("<keyword>:"")<value>(") and print only <value>.

1
  • 1
    Or s="Content"; grep -Po "(?<=$s\":\")[^\"]*" file
    – bu5hman
    Nov 8, 2019 at 22:02
1

jqless and perlless sledgehammer using OP's intended sed/awk

s="Content"; sed 's/[{}"]//g' file | awk -v s=$s -F ":" -v RS=',' '($1 == s) {print $2}'
1

OK, I admit that this is awful...

$ awk 'BEGIN {FPAT="\"[^\"]+\""; RS=","; pat=ARGV[1]; delete ARGV[1]} 
     $1 ~ pat {print $2} '       Content ex.json
"Value1"
0
$ jq -r '.Content' file
Value1
$ jq -r '.DeviceType' file
Value4

There is no reason to not install jq to parse the JSON properly, safely, and without having to care about decoding JSON-encoded strings manually etc.

The jq utility is available for download in a form that does not require root permissions for installation in your home directory (no external runtime dependencies).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.