python的新手,新手开发人员,首次调用
我正在调用一些JSON并将相关数据解析为csv。我无法弄清楚如何使用默认键填充中间的json Dict文件,因为其中很多都没有填充。当我尝试将内容解析为csv时,结果是KeyError。希望有任何建议!
谢谢。
更新:谢谢大家!我现在收到(制造商)的“ NoneType”错误:
import urllib2, json, csv, sys, os, codecs, re from collections import defaultdict output = 'bb.csv' csv_writer = csv.writer(open(output, 'w')) header = ['sku', 'name', 'description', 'image', 'manufacturer', 'upc', 'department', 'class', 'subclass'] csv_writer.writerow(header) i=1 while i<101: print i bb_url = urllib2.Request("http://api.remix.bestbuy.com/v1/products(sku=*)?show=sku,name,description,image,manufacturer,upc,department,class,subclass&format=json&sort=sku.asc&page=" + str(i) + "&pageSize=100&apiKey=*****************") bb_json = json.load(urllib2.urlopen(bb_url)) print bb_json for product in bb_json['products']: row = [] row.append(product['sku']) if product['name']: row.append(str((product['name']).encode('utf-8'))) else: row.append("") row.append(str(product.get('description',""))) row.append(str(product['image'])+ " ") if product['name']: row.append(str(product.get('manufacturer',"").encode('utf-8'))) else: row.append("") row.append(str(product.get('upc','').encode('utf-8'))) row.append(str((product['department']).encode('utf-8'))) row.append(str((product['class']).encode('utf-8'))) row.append(str((product['subclass']).encode('utf-8'))) csv_writer.writerow(row) i = i+1
您可以使用your_dict.get(key, "default value")而不是直接引用键。
your_dict.get(key, "default value")