I have read many articles here about this problem, but nothing I tried has helped to remove the extra backslash. I assume it is because the double quotes are getting added and then escaped. I am reading a csv from a lambda and the data in the csv is standard data
Ticker,Exchange,Date,Open,High,Low,Close,Volume
6A,BATS,12/5/2021,0.7103,0.712,0.6993,0.6999,113073
6B,BATS,12/5/2021,0.7103,0.712,0.6993,0.6999,113073
6C,BATS,12/5/2021,0.7103,0.712,0.6993,0.6999,113073
I dont mind the quotes showing in the outputted json, but I do mind the backslashes. Here is my code and current output (this is in a lambda with a layer)
import json
import awswrangler as wr
BUCKET_NAME = 'eod-candles-br'
DIRECTORY_PATH = 'candles'
FULL_PATH = f"s3://{BUCKET_NAME}/{DIRECTORY_PATH}"
def lambda_handler(event, context):
print(event)
raw_df = wr.s3.read_csv(path=FULL_PATH, path_suffix=['.csv'], use_threads=True)
df = raw_df.to_json(orient="records")
parsed = json.loads(df)
return {
'body': json.dumps(parsed, separators=(',', ':'))
}
Here is the output:
{
"body": "[{\"Ticker\":\"6A\",\"Exchange\":\"BATS\",\"Date\":\"12/5/2021\",\"Open\":0.7103,\"High\":0.712,\"Low\":0.6993,\"Close\":0.6999,\"Volume\":113073},{\"Ticker\":\"6B\",\"Exchange\":\"BATS\",\"Date\":\"12/5/2021\",\"Open\":0.7103,\"High\":0.712,\"Low\":0.6993,\"Close\":0.6999,\"Volume\":113073},{\"Ticker\":\"6C\",\"Exchange\":\"BATS\",\"Date\":\"12/5/2021\",\"Open\":0.7103,\"High\":0.712,\"Low\":0.6993,\"Close\":0.6999,\"Volume\":113073}]"
}
After changing the return code to the following (so that I am no longer using json.dumps), I dont have the backslashes, but I again have the spaces. So, return code is now like this:
return {
"statusCode": 200,
'body': (parsed)
}
result has no slashes, but has spaces again
{"statusCode": 200, "body": [{"Ticker": "6A", "Exchange": "BATS", "Date": "12/2/2021", "Open": 0.9, "High": 0.95, "Low": 0.83, "Close": 0.95, "Volume": 1200},
source https://stackoverflow.com/questions/75972739/extra-backslashes-seemingly-getting-added-by-json-dumps-or-json-loads
Comments
Post a Comment