简体   繁体   中英

Iterate over JSON file using python and post request

My Json is like this

[
 {
   "name":"abc"
   "emai":"hotmail"
 },
 {
  "name":"def"
  "emai":"gmail"
 }
]

I have to read one record at time and post request in 1st post request with data

'{
       "name":"abc"
       "emai":"hotmail"
     }'

in 2nd post request with data

'{
      "name":"def"
      "emai":"gmail"
     }'

i tried with this code,

import json
import requests
from requests.structures import CaseInsensitiveDict

url = "https://testurl.com"

headers = CaseInsensitiveDict()
headers["accept"] = "text/plain"
headers["username"] = "username"
headers["password"] = "password"
headers["Content-Type"] = "application/json"

with open("data.json", encoding='utf-8', errors='ignore') as json_data:
    for i in json_data:
        data = json.load(i, strict=False)
        idata = json.dumps(data) ## converting to string
        fData = idata.replace("'", '"') # replacing ' with "
        output = "'"+fData+"'" ## placing ' before and after json string which is mandatory in my case
        print(fData)
        # resp = requests.post(url, headers=headers, data=fData)
        # print(f"status_code: : {resp.status_code}, response : {resp.json}")

I'm getting error 'str' object has no attribute error, can you please suggest me what i have to change?

load all json, then loop through it

import json
import requests
from requests.structures import CaseInsensitiveDict

url = "https://testurl.com"

headers = CaseInsensitiveDict()
headers["accept"] = "text/plain"
headers["username"] = "username"
headers["password"] = "password"
headers["Content-Type"] = "application/json"
with open("data.json", encoding='utf-8', errors='ignore') as json_string:
    json_data = json.load(json_string.read(), strict=False)
    for i in json_data:
        data = i
        idata = json.dumps(data) ## converting to string
        fData = idata.replace("'", '"') # replacing ' with "
        output = "'"+fData+"'" ## placing ' before and after json string which is mandatory in my case
        print(fData)
        # resp = requests.post(url, headers=headers, data=fData)
        # print(f"status_code: : {resp.status_code}, response : {resp.json}")

I guess you want to convert your JSON data to python structure first and then process it, something like:

import json

with open("data.json", encoding='utf-8', errors='ignore') as json_data:
    data = json.loads(json_data.read())
    for obj in data:
        resp = requests.post(url, headers=headers, data=obj)
        print(f"status_code: : {resp.status_code}, response : {resp.json}")

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