Python for loop posting json to url?

浪尽此生 提交于 2021-01-29 16:10:46

问题


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"]
             }
         }]
    })

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?


回答1:


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"]):
     # ...

Edit:

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"]
                }
             }]
     })


来源:https://stackoverflow.com/questions/21690567/python-for-loop-posting-json-to-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!