How remove from my json dump backslashes?
my python code is :
@sio.on('donation')
def on_message(data):
y = json.loads(data)
with open('donate.json', 'w') as outfile:
json.dump(data, outfile)
if i make print all fine and no backslashes!But if i open my json file he look like this :
"{\"id\":107864345,\"alert_type\":\"1\",\"is_shown\":\"0\",\"additional_data\":\"{\\\"randomness\\\":811}\",\"billing_system\":\"fake\",\"billing_system_type\":null,\"username\":\"test24\",\"amount\":\"1.00\",\"amount_formatted\":\"1\",\"amount_main\":1,\"currency\":\"USD\",\"message\":\"aaaaaa aaaa\",\"header\":\"\",\"date_created\":\"2022-12-17 21:57:10\",\"emotes\":null,\"ap_id\":null,\"_is_test_alert\":true,\"message_type\":\"text\",\"preset_id\":0}"
i try all what i know
CodePudding user response:
Your code, annotated:
def on_message(data):
When this function is called, it is provided with the argument data
, which is a string containing the JSON encoding for a complex object.
y = json.loads(data)
Now data
is still the same string, and y
is the complex object which was represented by data
.
with open('donate.json', 'w') as outfile:
json.dump(data, outfile)
json.dump
takes a data object and turns it into a string. With two arguments, as here, it writes the string to a file. But despite its name, data
is not the dara object. It's a string. The data object is y
.
json.dump
will convert any Python object with a JSON representation to a string representing that object, and a string can be represented in JSON. So in this case, the string in data
is encoded as a JSON representation. That means that the string must be enclosed in double quotes and any special characters escaped.
But that's not what you wanted. You wanted to dump the data object, which you have named y
. Changing that line to
json.dump(y, outfile)
Will probably do what you want.
But if you just wanted to write out the string, there wasn't much point converting it to JSON and back to a string. You could just write it out:
outfile.write(data)
Then you can get rid of y
(unless you need it somewhere else).