以下代码有效但只按照以下内容在索引处上传了一个结果,请参阅['result'][2]["text"]
- 在索引2上完整地上传'text'
结果:
with open("test.json") as json_file:
data = json.load(json_file)
connection.request('POST', '/1/batch', json.dumps({
"requests": [{
"method": "POST",
"path": "/1/classes/test",
"body": {
"playerName": data['results'][2]["text"],
"Url": data['results'][2]["Url"],
"Amount": data['results'][2]["Amount"]
}
}]
})
如何在此处循环浏览所有json结果([0]
至eof
),而不必更改['results'][0]["text"]
,按Enter键,['results'][1]["text"]
按Enter键,{ {1}}按回车等?
答案 0 :(得分:0)
一个简单的for
将解决它:
with open("test.json") as json_file:
data = json.load(json_file)
for entry in data['results']:
connection.request('POST', '/1/batch', json.dumps({
"requests": [{
"method": "POST",
"path": "/1/classes/test",
"body": {
"playerName": entry["text"],
"Url": entry["Url"],
"Amount": entry["Amount"]
}
}]
})
如果您确实需要索引编号,可以使用enumerate()
功能:
for index, entry in enumerate(data["results"]):
# ...
修改强>
如果'/1/batch'
表示'/2/batch'
(例如拼写错误),那么您需要使用enumerate()
。例如:
with open("test.json") as json_file:
data = json.load(json_file)
for index, entry in enumerate(data['results']):
connection.request('POST', '/%d/batch' % (index), json.dumps({
"requests": [{
"method": "POST",
"path": "/%d/classes/test" % (index),
"body": {
"playerName": entry["text"],
"Url": entry["Url"],
"Amount": entry["Amount"]
}
}]
})