问题描述:

I'm dealing with some JSON and parsing it in Python I have this one part I can't seem to figure out the syntax for. So here's my JSON:

u'line_items':[

{

u'product':{

u'weight':0.5,

u'regular_price':u'$40.00',

u'name_short':u'Name',

u'currency':u'USD',

},

{

u'product':{

u'weight':None,

u'regular_price':u'$17.00',

u'name_short':u'Map of the World Jumbo Puzzle',

u'currency':u'USD',

}

]

And sometimes there are more than one product in the line_items list. What is the syntax to iterate through the product dicts in line_items? I'm trying

for j in i['line_items']

product = j['product']

but it only works for the first product. Also, i serves as an enumerator for a larger dict that includes line_items.

网友答案:

Since you haven't given us the full data structure I am only guessing , but, ... you only have one level of lists. Enumerate it to get the product dicts.

for item in i['line_items']:
    product = item['product']
    weight = product['weight']
    # sanity check
    print("product: %s, weight: %s" % (product['name_short'], weight))
网友答案:

Iterate over products:

for product in i['line_items']:
    # prints single products
    print product

Or if you need the product index (for index_in_list in following examples):

for index_in_list in range(len(i['line_items'])):
    # prints single products
    print i['line_items'][index_in_list]

Iterate over a single product's keys:

for product_key in i['line_items'][index_in_list]:
    # prints product info
    print product_key, '-', i['line_items']['product'][product_key]

Or easier:

for product_key, product in i['line_items'][index_in_list].iteritems():
    # still has access to 'product_key' if you want to modify it.
    print product_key, '-', product
相关阅读:
Top