0

Here is the output from the response I am trying to parse:

[{"name":"UsedMemory","value":{"value":"35054384","type":"java.lang.Long"}},
{"name":"FreeMemory","value":{"value":"7085264","type":"java.lang.Long"}},{"name":"Heap","value":{"value":"42139648","type":"java.lang.Long"}},{"name":"UpTime","value":{"value":"3350544","type":"java.lang.Long"}},{"name":"ProcessCPU","value":{"value":"0.3625301325982962","type":"java.lang.Double"}},{"name":"GcCount","value":{"value":"224","type":"java.lang.Long"}},{"name":"GcTime","value":{"value":"335","type":"java.lang.Long"}}]

I am storing the response in a shell variable called $jvmStats and expect to be able to retrieve a value from it based on name like this:

$jvmStats | python -c "import sys, json; print json.load(sys.stdin)['UsedMemory']"

but the response I get is:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: list indices must be integers, not str

Pretty new to working with JSON and unfortunately don't have the ability to use jq on this system - can some one point out the problem to me? This seems like a fairly standard approach according to all the other answers I see here - so perhaps nested value parts is the problem?

1 Answer 1

4

Try this:

jvmStats | python -c "import sys, json; print json.load(sys.stdin)[0]['name']"

This is because your JSON is first a list and then a dictionary, so you need to index the list first and then the key of the dictionary.

Also, you can only index JSON by its key, not its value.

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

1 Comment

looks better - thanks! Beginning to see that the format is inconsistent with what I want to achieve via python. I essentially want a one liner to output a bunch of k=v pairs. I am not the provider of the JSON and there is no guarantee there lines will come out in the same order each time - thus doing things by indices is going to be tough. I am probably better with a sed command!

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.