简体   繁体   中英

Iterating over each json in the array

I have a query for SQL from which I need to prepare for each line json which I will use as a payload json for HTTP request. This json I need to rebuild a little bit, because for some keys I need to add another level of json. This is not a problem.

The problem is that I don't know how to iterate over each such object/row in the json. I need to do a for each and output as payload to separate HTTP requests. At this point I have:

result = []

for row in rows:
    d = dict()
    d['id'] = row[40]
    d['email'] = row[41]
    d['additional_level'] = dict()
    d['additional_level']['key'] = row[42]
    result.append(d)

payload = json.dumps(result, indent=3)

At this point, print(payload) looks like this:

[
   {
      "id": 01,
      "email": "someemail01@gmail.com"
      "additional_level": {
         "key": 10
      }
   },
   {
      "id": 02,
      "email": "someemail02@gmail.com"
      "additional_level": {
         "key": 10
      }
   }
]

Now I want to make a separate payload json from each id and use in request http. How can I refer to them and how to make for loop to separately refer to each "object" separately?

You can dump each object separately:

for row in rows:
    d = dict()
    d['id'] = row[40]
    d['email'] = row[41]
    d['additional_level'] = dict()
    d['additional_level']['key'] = row[42]
    result.append(json.dumpsd, indent = 3)

And then iterate over them and use them individually:

for payload in result:
    # Use payload for a request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM