0

I want to parse in bash the json-string like this:

{"710":{"sysKey":"ENTER"},"230":{"sysKey":"DELETE"},"804":{"sysKey":"ADD"}}

My task is to find the value of key {"sysKey":"DELETE"} and get 230

My try:

echo '{"710":{"sysKey":"ENTER"},"230":{"sysKey":"DELETE"},"804":{"sysKey":"ADD"}}' | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["sysKey"]["DELETE"];'

Help me please!

  • 2
    So are you limited to bash or can you use python? Your tags are confusing. – Anonymous Aug 03 '15 at 23:42
  • I can use python in bash commands like this: echo '{"key":"value"}' | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["key"];' – user3025172 Aug 03 '15 at 23:50
  • if you can advice me how to parse this string without python, I would be very grateful – user3025172 Aug 03 '15 at 23:51
  • 4
    `230` is the key not the value. You can't lookup by value. You need to walk for values. So you get to walk all the values looking for a value that is a dictionary with a `sysKey` key that has `DELETE` as its value. – Etan Reisner Aug 03 '15 at 23:52
  • 1
    Look into the `jq` utility. http://stackoverflow.com/questions/18592173/select-objects-based-on-value-of-variable-in-object-using-jq – engineerC Aug 04 '15 at 00:18

1 Answers1

1

If the only 'DELETE' you will pipe in is the one under 'sysKey', you could do this:

echo '{"710":{"sysKey":"ENTER"},"230":{"sysKey":"DELETE"},"804":{"sysKey":"ADD"}}' | python -c 'import json,sys;obj=json.load(sys.stdin);obj=dict((z,x) for x, y in obj.items() for z in y.values());print obj["DELETE"];'

But that's pretty ugly by just about anybody's standard, I think...

Patrick Maupin
  • 8,024
  • 2
  • 23
  • 42
  • on the advice of Etan Reisner, my decision was: `echo {"710":{"sysKey":"ENTER"},"230":{"sysKey":"DELETE"},"804":{"sysKey":"ADD"}} | python -c $'import json,sys;obj=json.load(sys.stdin);\nfor key in obj.keys():\n\tif obj[key]["systemName"]=="DELETE": print key'` – user3025172 Aug 04 '15 at 00:33