问题描述
以下代码有效,但仅按如下所示在索引处上载一个结果,请参见 ['result'] [2] ["text"]
-上载'文本
在索引2处的结果完美:
The following code works but only uploads the one result at the index as per the below, see ['result'][2]["text"]
- which uploads the 'text'
result at index 2 perfectly:
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, ['results'] [2] [文字"]
按Enter等?
How can I loop through all of the json results here ([0]
to eof
) rather than having to change ['results'][0]["text"]
, press enter, ['results'][1]["text"]
press enter, ['results'][2]["text"]
press enter etc?
推荐答案
简单的 for
会解决该问题:
A simple for
will solve it:
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"]
}
}]
})
如果您确实需要索引号,则可以使用 枚举()
函数:
If you really need the index number, you can use the enumerate()
function:
for index, entry in enumerate(data["results"]):
# ...
如果用'/1/batch'
表示'/2/batch'
(例如,错字),那么您将需要使用 enumerate()
.例如:
If by '/1/batch'
you mean '/2/batch'
(eg. typo), then you will need to use enumerate()
. Eg:
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"]
}
}]
})
这篇关于Python for循环将json发布到url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!