在此代码中使用data[attach.]
.json的最有效/最省力的代码是什么:
with open('slack.json') as slackAttachment:
data = json.load(slackAttachment)
with open('slack2.json') as slackAttachment:
data2 = json.load(slackAttachment)
with open('slack3.json') as slackAttachment:
data3 = json.load(slackAttachment)
with open('slack4.json') as slackAttachment:
data4 = json.load(slackAttachment)
data["attachments"][0]["title"] = country
itemname = item.get('Title', {})
if itemname:
newitemword = item['seoTitle']
data["attachments"][0]["text"] = "" + newitemword + ""
else:
data["attachments"][0]["fields"].append({
"value": '*Item name not found*',
"short": True,
})
不仅有这两个数据[“ attachments”] [0],而且还有大约xx个。
基本上我不想做的是:
data["attachments"][0]["text"] = "" + newitemword + ""
data2["attachments"][0]["text"] = "" + newitemword + ""
data3["attachments"][0]["text"] = "" + newitemword + ""
data4["attachments"][0]["text"] = "" + newitemword + ""
我想知道是否还有其他有效的方法可以用比上面的代码少的代码来解决它,并且仍然能够自己使用所有这些slacks.json?
编辑:
webhook0 = 'HELLO'
webhook1 = 'WORLD
webhook2 = 'STACK'
data = {}
file_numbers = range(0, 3) # I assume the numbers are from 1 to 4, but you can change this.
for file_number in file_numbers: # go overf file numbers
file_name = 'slack' + str(file_number) + '.json' # create file name from number
with open(file_name) as slackAttachment:
data[file_number] = (json.load(slackAttachment)) # append file json to data list
webhook_number = 'webhook' + str(file_number)
print(webhook_number)
# data is now complete
# you can use data[file_number] to access the corresponding json
for file_number in file_numbers:
答案 0 :(得分:1)
您可以将所有数据存储在一个"devtools": {
"preferences": {
"Inspector": {
"drawerSplitViewState": "{\"horizontal\":{\"size\":363,\"showMode\":\"Both\"}}"
}
}
}
中。
"devtools": {
"preferences": {
"Inspector.drawerSplitViewState": "{\"horizontal\":{\"size\":363,\"showMode\":\"Both\"}}",
}
}
每次要访问文件数据时,请使用dict
。
因此,要访问第一个data = {}
file_numbers = range(1, 5) # I assume the numbers are from 1 to 4, but you can change this.
for file_number in file_numbers: # go overf file numbers
file_name = 'slack' + str(file_number) + '.json' # create file name from number
with open(file_name) as slackAttachment:
data[file_number] = (json.load(slackAttachment)) # append file json to data list
# data is now complete
# you can use data[file_number] to access the corresponding json
for file_number in file_numbers:
data[file_number]["attachments"][0]["title"] = country
itemname = item.get('Title', {})
if itemname:
newitemword = item['seoTitle']
data[file_number]["attachments"][0]["text"] = "" + newitemword + ""
else:
data[file_number]["attachments"][0]["fields"].append({
"value": '*Item name not found*',
"short": True,
})
,请使用data[<file_number>]