【发布时间】:2021-09-26 01:35:32
【问题描述】:
使用 JSON 和 Python 相对较新,但在尝试附加到现有 JSON 对象时遇到问题。首先,一些伪代码:
- 想为每个追加使用一个 JSON“模板”,以便创建
- 新列表中的第一项将始终是此模板(索引 0)
- 找到新记录后,模板会附加到对象中,然后填充
我已经尝试过 json.update 和 dict.append 并且只是连接到一个字符串,但我总是让列表索引超出范围(当前错误,下面的代码)或附加错误。
请帮忙!
def parse(self, response):
# Create Store JSON template
unit_JSON_template = {
"Store": [
{
"ID": "",
"Seller":
{
"Name": ""
},
"Detail":
{
"StoreURL": "",
"Title": "",
"Stock": "",
"Other": "",
"Images": [
{
"Url": "",
"Encode": "",
"Title": ""
}
],
"Request":
{
"DateTime": "",
"RequestHeaders": "",
"ResponseHeaders": ""
}
}
}
],
}
# Convert template string to JSON
unit_JSON_str = json.dumps(unit_JSON_template, indent = 4, separators = (", ", ": "), sort_keys = False)
print(unit_JSON_str)
unit_JSON_obj = json.loads(unit_JSON_str)
unit_JSON = unit_JSON_obj
# Create identifying information
record = response.url.split("/")[2] + "-" + response.url.split("/")[-2]
record_timestamp = datetime.now().strftime("%m%d%Y%-H%M%S")
page_filename = f'{record}-{record_timestamp}.html'
screenshot_filename = f'{record}-{record_timestamp}.png'
# Parse data, load to JSON object for Insert to SQL
data_units = response.xpath("//candy-stores")
print("Units Found: " + str(len(data_units)))
# Loop over each object and insert into JSON object (index 0 always template above)
for i, data_unit in enumerate(data_units):
i_1 = i + 1 #do this since template is always index 0
unit_JSON.update(unit_JSON_obj)
print(json.dumps(unit_JSON, indent=4))
unit_JSON['Store'][i_1]['Detail']['Title'] = "Store Name"
unit_JSON['Store'][i_1]['Detail']['StoreURL'] = "Unit"
unit_JSON['Store'][i_1]['Detail']['Request']['DateTime'] = "12:00pm"
unit_JSON['Store'][i_1]['Detail']['Other'] = "Additional Data"
unit_JSON['Store'][i_1]['Seller']['Name'] = "ABC Candy"
【问题讨论】:
-
你能添加一个打印出来的
data_units吗?