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!

5
  • 2
    So are you limited to bash or can you use python? Your tags are confusing. Commented Aug 3, 2015 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"];' Commented Aug 3, 2015 at 23:50
  • if you can advice me how to parse this string without python, I would be very grateful Commented Aug 3, 2015 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. Commented Aug 3, 2015 at 23:52
  • 1
    Look into the jq utility. stackoverflow.com/questions/18592173/… Commented Aug 4, 2015 at 0:18

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.