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.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Riz
  • 49

4 Answers4

0

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>.

0

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}'
bu5hman
  • 4,756
0

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"
JJoao
  • 12,170
  • 1
  • 23
  • 45
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).

Kusalananda
  • 333,661