python create JSON string抛出异常

时间:2016-01-03 23:08:35

标签: python json python-2.7 scrapy

这是我得到的错误

ERROR:scrapy.core.scraper:Error processing {'action': u'Rent',
 'ad_images': [bla bla bla],
 'ad_link': u'does_not_exit_in_this_website',
 'ad_title': u'boa bra bra',
 'agent_fees': 2300.0,
 'amenities': u'boa bra bra',
 'area': u'does_not_exit_in_this_website',
 'bathrooms': 1.0,
 'bedrooms': u'1',
 'building': u'',
 'category': u'Apartment',
 'city': -1,
 'commission': u'does_not_exit_in_this_website',
 'coordinates': u'does_not_exit_in_this_website',
 'country': u'',
 'ded_licence_number': u'718652',
 'description': u'Description:',
 'furnished': u'No',
 'latitude': -1,
 'link': u'bla bla bla',
 'location': u'',
 'longitude': -1,
 'mobile': u'does_not_exit_in_this_website',
 'payment_type': u'does_not_exit_in_this_website',
 'phone': u'',
 'phoneticarea': u'does_not_exit_in_this_website',
 'phoneticbuilding': u'does_not_exit_in_this_website',
 'phoneticsubarea': u'does_not_exit_in_this_website',
 'posting_date': u'2016-01-04',
 'price': u'does_not_exit_in_this_website',
 'price_sqft': u'does_not_exit_in_this_website',
 'property_reference': u'Ramzi',
 'rent_is_paid': u'Quarterly',
 'rera_registration_number': u'15691',
 'security_deposit': u'does_not_exit_in_this_website',
 'size': 1000.0,
 'source': u'dubizzleproperty',
 'subarea': u'does_not_exit_in_this_website',
 'trade_name': u'BLUE HOME PROPERTIES',
 'type': u'does_not_exit_in_this_website',
 'yearly_cost': 43000.0}
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "bra bra bla/pipelines.py", line 70, in process_item
    body = '{"building": "{0}", "area" : "{1}", "subarea" : "{2}", "country" : "{3}", "city" : "{4}", "payment_type" : "{5}", "category" : "{6}", "phoneticbuilding" : "{7}", "phoneticarea" : "{8}", "phoneticssubarea": "{9}" }'.format(building, area, subarea, country, city, payment_type, category, phoneticbuilding, phoneticarea, phoneticssubarea)
KeyError: '"building"'

如果您想知道管道文件的第70行,请转到:

body = '{"building": "{0}", "area" : "{1}", "subarea" : "{2}", "country" : "{3}", "city" : "{4}", "payment_type" : "{5}", "category" : "{6}", "phoneticbuilding" : "{7}", "phoneticarea" : "{8}", "phoneticssubarea": "{9}" }'.format(building, area, subarea, country, city, payment_type, category, phoneticbuilding, phoneticarea, phoneticssubarea)

2 个答案:

答案 0 :(得分:1)

正如@arthur所说,你需要用两个括号替换单个花括号。我想补充一点,你应该在将成为JSON字符串的键值的文本中执行它:

例如(字符串的简短版本),替换:

body = '{"building": "{0}", "area" : "{1}" }'.format(building, area)

使用:

body = '{{"building": "{0}", "area" : "{1}" }}'.format(building, area)

答案 1 :(得分:0)

尝试转义正文的非格式{}括号。

修改:这意味着将其替换为{{}}。见How can I print literal curly-brace characters in python string and also use .format on it?