I'm making HTTPSConnection
using (Python)Unirest
and the response have charecters like "
, \
and \n
so I hard-coded my python code and finally i got the right response without any characters on console using sys.stderr.write(data2)
@router.get("/data", status_code=status.HTTP_200_OK)
async def data_detail(type: str ):
try:
conn = http.client.HTTPSConnection("example.com")
conn.request("GET", "/test.php?type=" type)
res = conn.getresponse()
data = res.read()
data2 = data.decode("utf-8")
data2 = data2[1:-1]
data2 = data2.replace("\\n", '')
data2 = data2.replace("\\", '')
res = {
"status" : "OK" ,
"result" : data2
}
return JSONResponse(res)
except Exception as e:
raise HTTPException(status_code=400, detail="Error")
now when i return data
to user the backslash \
back again to the the data response
the data i received from third party is :
"{\"list1\":[{\"one\":\"one\",\"tow\":\"tow\",\"three\":\"three\"},{\"test1\":\"test1\",\"test2\":\"test2\",\"test3\":\"test3\"},],\"list2\":[]}\n"
after replacing characters i got this on system console
{"list1":[{"one":"one","tow":"tow","three":"three"},{"test1":"test1","test2":"test2","test3":"test3"}],"list2":[]}
but when i add this data to final json response the backslashes back again to the output and all the data stored as one value in result
any solution for this problem
CodePudding user response:
Decode the JSON.
First import json
and then try replacing:
data2 = data2[1:-1]
data2 = data2.replace("\\n", '')
data2 = data2.replace("\\", '')
by
data2 = json.loads(data2)
After this, you final json response will be constructed correctly.
You should use json.dumps(data2)
to print this data to console. In general, use json.dumps
to pretty print python data as JSON.
See https://docs.python.org/3/library/json.html for more help in handling JSON in python.
CodePudding user response:
You are never replacing a single backslash. Do you need to add a line like
data2 = data2.replace("\", '')