Python get JSON object by index
Question: I have a JSON file that looks something like this:

    
    
    { data:
          { 123:
    
          { 212:
    
          { 343: 
    

In python I load the JSON using json.loads(r.text). The strings inside the
data object are not guaranteed to be those but can be any number. What I want
to be able to do is to be able to get those numbers so I can store then in an
array. In this example I want the array to look like [123,212,343]. Is there
anyway to do this since they are nested objects and not a JSON array?

Thanks


Answer: Very briefly:

    
    
    #!/usr/bin/env python
    
    import json
    
    foo = json.loads('{"123": null, "234": null, "456": null}')
    print map(int, foo.keys())
    

The list `foo.keys()` will not be in the same order as presented in the JSON
object (or its string representation).

If you need to preserve ordering, you might try the following modification:

    
    
    #!/usr/bin/env python
    
    import json, collections
    
    foo = json.loads('{"123": null, "234": null, "456": null}', object_pairs_hook=collections.OrderedDict)
    print map(int, foo.keys())
    

As you iterate over the list of keys, you can do a reverse lookup on an
individual key in the usual way.

Note that you will likely want to convert the integer-key back to a Python
string with `str()`, in order to retrieve its associated value. If you just
want the list of keys for lookups, however, and you don't really need the
actual integer values, you can skip the initial `map` call and just preserve
the keys as strings.

