0

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

1
  • 4
    that's not valid JSON. Please show a complete example Commented Jan 7, 2015 at 22:46

1 Answer 1

2

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.

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.