0

I have to send a string request to a backend. I have 2 variables which I have to format inside the string with the request. The request has to look like this:

"{\"MachineType\":0,\"BrokenMachines\":6}"

I have 2 variables called type and count which I want to put inside the request (the 0 in the example would be type and the 6 would be count). I've tried almost everything I know and I'm still not able to get the string with the escaped characters, python converts them to literals. These are some solutions I tried with their results:

Attempt:

("{\"MachineType\":" + str(type) + ",\"BrokenMachines\":" + str(count) + "}").encode('unicode_escape').decode('ASCII')

Result:

'{"MachineType":1,"BrokenMachines":6}'

Attempt:

'{{\"MachineType\":{},\"BrokenMachines\":{}}}'.format(type, count).encode('unicode_escape').decode('ASCII')

Result:

'{"MachineType":1,"BrokenMachines":6}'

Attempt:

"{{\\\"MachineType\\\":{},\\\"BrokenMachines\\\":{}}}".format(type, count)

Result:

'{\\"MachineType\\":1,\\"BrokenMachines\\":6}'

How can I make it work?

Nahue
  • 320
  • 2
  • 18
  • you didn't try `'{\\"MachineType\\":1,\\"BrokenMachines\\":6}'` or `r'{\"MachineType\":1,\"BrokenMachines\":6}'` – Jean-François Fabre Oct 09 '18 at 18:28
  • Also, It looks like you are trying to output JSON. If that's the case, you should use the json module and not try and do this yourself – Michael Robellard Oct 09 '18 at 18:30
  • `'{\\"MachineType\\":1,\\"BrokenMachines\\":6}` **is the correct output**. You are confusing the string representation for the value. Try *printing* the value instead. You have single backslashes in the value, but the string representation (which is valid Python syntax to reproduce the value) uses doubled backslashes because single backslashes would lead to .... your output in your earlier attempts. – Martijn Pieters Oct 09 '18 at 18:33
  • I know this is 4 years old, but type is a reserved word. – Shmack Nov 29 '22 at 18:32

1 Answers1

0

You can use either single or double quote to signify a string so if you string needs to contain one then use the other. Also you can use an r string to escape all special characters.

r'"{\"MachineType\":0,\"BrokenMachines\":6}"'

BigGerman
  • 525
  • 3
  • 11
  • I know, I used single quotes but I have to pass a string that show a \" inside, because the backend processes the string and if it's not escaped it disappears... – Nahue Oct 09 '18 at 18:49
  • It will show the backslash. That is what the 'r' denotes on the string, a raw string. So `print(r'"{\"MachineType\":0,\"BrokenMachines\":6}"')` will print out "{\"MachineType\":0,\"BrokenMachines\":6}" in the console – BigGerman Oct 09 '18 at 18:53