2

I have the following JSON string:

jsonString = {'result': {'animals': {'Dogs': True, 'Cats': True}}

So in Python I know I can do:

animals= jsonString['result']['animals']

To get the value of 'Dogs' or 'Cats'. And:

animals= jsonString['result']['animals']['Dogs']

To get the value of 'Dogs' or 'Cats'.

However, when I try print (jsonString['result']['animals']) I get:

{'Dogs': True, 'Cats': True}

Question

How do I get the all the animals, without values, dynamically?

Thanks.

6
  • 1
    What result are you looking for? something like ['Dogs', 'Cats']? Commented Mar 9, 2016 at 15:06
  • jsonString['result']['cats'].keys()? Commented Mar 9, 2016 at 15:08
  • 2
    you are actually using a dict and this has nothing to do with json, and I think you want .keys() to get the keys of the dict, however the print statement you provided is not a valid python command Commented Mar 9, 2016 at 15:09
  • Well, I should have mentioned .keys(). This returns the "dict_keys(['Dogs','Cats'])" output. I am looking for something like: ['Dogs', 'Cats'] Commented Mar 9, 2016 at 15:13
  • 2
    This is the answer list(jsonString["result"]["cats"].keys()) but accept Tadhg McDonald-Jensen's answer; it's more informative. Commented Mar 9, 2016 at 15:24

1 Answer 1

3

First off when the data is loaded from json it creates a dict object, so all the methods described in the documentation are usable including keys:

print(jsonString['result']['cats'].keys())

you can see a list of all the possible methods with dir(dict) or dir(jsonString) and get help on any of them with the built in function:

>>> help(dict.keys)
Help on method_descriptor:

keys(...)
    D.keys() -> a set-like object providing a view on D's keys
Sign up to request clarification or add additional context in comments.

Comments

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.