0

I want to extract the value of pt & userId in a variable in shell script.

I've below value set in a varibale which comes dynamically & need to extract pt & userId

{"pt":"PT-24fesxPGJIHOe714iaMV-13dd3872781-sin_pos","userId":"66254363666003"}

Can any one tell me how to extract these values in shell script?

Note: I don't want to use JSON parser just to parse 2 strings.

Thanks!

graphite
  • 2,920
  • 22
  • 40
Freephone Panwal
  • 1,547
  • 4
  • 21
  • 39

2 Answers2

1

This string appears to be a JSON string and its better to use dedicated JSPN parser like underscore for parsing this text. Once underscore cli is installed you can do:

# extract pt
echo $jsonStr | underscore select '.pt'

# extract userId
echo $jsonStr | underscore select '.userId'

Though not recommended but if you really want to parse it in shell you can use awk like this:

 awk -F, '$1 ~ "pt" {gsub(/[^:]+:"|"/, "", $1); print $1}
          $2 ~ "userId" {gsub(/[^:]+:"|"}/, "", $2); print $2}'

OR even simpler:

 awk -F'"' '{print $4 "\n" $8}'

Output:

PT-24fesxPGJIHOe714iaMV-13dd3872781-sin_pos
66254363666003
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You can use following script

var={"pt":"PT-24fesxPGJIHOe714iaMV-13dd3872781-sin_pos","userId":"66254363666003"}
echo $var
pt=`echo $var|cut -d, -f1|awk -F':' '{ print $2 }'`
echo $pt
userId=`echo $var|cut -d, -f2|awk -F':' '{ print $2 }'|tr -d '}'`
echo $userId

In this script stores values in 2 variables "pt" and "userId", which you can use.

orNehPraka
  • 413
  • 2
  • 6
  • 14
  • It prints double quotes as well. How to strip off double quotes? My var variable contains double quotes due to which the extracted values also have double quotes. Can you please tell me how to strip off quotes? – Freephone Panwal Apr 04 '13 at 06:21
  • Use can use following - pt=`echo $var|cut -d, -f1|awk -F':' '{ print $2 }'|tr -d '"'` userId=`echo $var|cut -d, -f2|awk -F':' '{ print $2 }'|tr -d '}'|tr -d '"'` Let me know, that it is working or not. – orNehPraka Apr 04 '13 at 06:26