0

Hi I am trying to dump json to file using python where I saw "\" Example is below

{\"eventVersion\":\"1.05\",\"userIdentity\":{\"type\":\"IAMUser\",\"principalId\":\"AIDAJJM7GL72KEP64JVYG\",\"arn\":\"arn:aws:iam::5030689XXXX:user/abhi\",\"accountId\":\"5030689XXX\",\"accessKeyId\":\"ASIAXKIJ7FDUSM\",\"userName\":\"abhipandey\",\"sessionContext\":{\"attributes\":{\"mfaAuthenticated\":\"false\",\"creationDate\":\"2019-08-10T09:49:34Z\"}},\"invokedBy\":\"signin.amazonaws.com\"},\"eventTime\":\"2019-08-10T09:49:58Z\",\"eventSource\":\"sns.amazonaws.com\",\"eventName\":\"ListSubscriptions\",\"awsRegion\":\"us-west-2\",\"sourceIPAddress\":\"103.214.189.229\",\"userAgent\":\"signin.amazonaws.com\",\"requestParameters\":{\"nextToken\":\"AAHLcEnGPYVVsORCkUMXjJF0FHnYLalrN+BfvizlKzkWvg==\"},\"responseElements\":null,\"requestID\":\"247dc857-993e-5677-a8df-9d9f0cb805dd\",\"eventID\":\"5e726329-2342-48e6-8e00-5c2fa9856ed9\",\"eventType\":\"AwsApiCall\",\"recipientAccountId\":\"50306896\"}

Can I get help to remove this backslash from everywhere.

Ajay Gupta
  • 127
  • 3
  • 13

2 Answers2

0
import json
remove_bs = r'{\"eventVersion\":\"1.05\",\"userIdentity\":{\"type\":\"IAMUser\",\"principalId\":\"AIDAJJM7GL72KEP64JVYG\",\"arn\":\"arn:aws:iam::503068961001:user/abhipandey\",\"accountId\":\"503068961001\",\"accessKeyId\":\"ASIAXKIJ7FDUSMHIHV7G\",\"userName\":\"abhipandey\",\"sessionContext\":{\"attributes\":{\"mfaAuthenticated\":\"false\",\"creationDate\":\"2019-08-10T09:49:34Z\"}},\"invokedBy\":\"signin.amazonaws.com\"},\"eventTime\":\"2019-08-10T09:49:58Z\",\"eventSource\":\"sns.amazonaws.com\",\"eventName\":\"ListSubscriptions\",\"awsRegion\":\"us-west-2\",\"sourceIPAddress\":\"103.214.189.229\",\"userAgent\":\"signin.amazonaws.com\",\"requestParameters\":{\"nextToken\":\"AAHLcEnGPYVVsORCkUMXjJF0FHnYLalrN+BfvizlKzkWvg==\"},\"responseElements\":null,\"requestID\":\"247dc857-993e-5677-a8df-9d9f0cb805dd\",\"eventID\":\"5e726329-2342-48e6-8e00-5c2fa9856ed9\",\"eventType\":\"AwsApiCall\",\"recipientAccountId\":\"503068961001\"}'

clear = remove_bs.replace("\\", "")
json_data = json.loads(clear)

How you maybe created this data:

import json
not_encoded = {"created_at":"Fri Aug 08 11:04:40 +0000 2014"}
encoded_data = json.dumps(not_encoded)
print(encoded_data)
>>>{"created_at": "Fri Aug 08 11:04:40 +0000 2014"}
double_encode = json.dumps(encoded_data)
print(double_encode)
>>>"{\"created_at\": \"Fri Aug 08 11:04:40 +0000 2014\"}"

EDIT:

IF you already loaded the data unload replace load back

json_string = json.dumps(json_data)
new_clear = json_string.replace("\\", "")
json_data = json.loads(new_clear)
print(json_data)
Fabian
  • 1,130
  • 9
  • 25
0

It looks like You have just escaped string representation without backslashes.

If you confirm that backslashes are present in string, use following code to get rid of them:

json_str = json_str.replace('\\', '')
elklepo
  • 509
  • 4
  • 17