Parsing muilti dimensional Json array to Python
After you parse the JSON, you will end up with a Python dict. So, suppose the above JSON is in a string named input_data:
import json# This converts from JSON to a python dictparsed_input = json.loads(input_data)# Now, all of your static variables are referenceable as keys:secret = parsed_input['secret']minutes = parsed_input['minutes']link = parsed_input['link']# Plus, you can get your bookmark collection as:bookmark_collection = parsed_input['bookmark_collection']# Print a list of names of the bookmark collections...print bookmark_collection.keys() # Note this contains sublinks, so remove it if needed# Get the name of the Boarding Pass bookmark:print bookmark_collection['boarding_pass']['name']# Print out a list of all bookmark links as:# Boarding Pass# * 1: http://www.1.com/# * 2: http://www.2.com/# ...for bookmark_definition in bookmark_collection.values(): # Skip sublinks... if bookmark_definition['name'] == 'sublinks': continue print bookmark_definition['name'] for bookmark in bookmark_definition['bookmarks']: print " * %(name)s: %(link)s" % bookmark# Get the sublink definition:sublinks = parsed_input['bookmark_collection']['sublinks']# .. and print themprint sublinks['name']for link in sublinks['link']: print ' *', link
Hmm, doesn't json.loads do the trick?
For example, if your data is in a file,
import jsontext = open('/tmp/mydata.json').read()d = json.loads(text)# first level fieldsprint d['minutes'] # or 'secret' or 'link'# the names of each of bookmark_collections's itemsprint d['bookmark_collection'].keys()# the sublinks section, as a dictprint d['bookmark_collection']['sublinks']
The output of this code (given your sample input above) is:
20[u'sublinks', u'free_link', u'boarding_pass']{u'link': [u'http://www.1.com', u'http://www.2.com', u'http://www.3.com'], u'name': u'sublinks'}
Which, I think, gets you what you need?