How do you remove backslashes from a string.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By stubbsy345
:warning: Old Version Published before Godot 3 was released.

I have a string that I receive from a HTTP request. It’s a json but comes in as a string with \ in front of the speech marks as you would expect in for a string. BUT I want to store this as a JSON. I am having a lot of trouble removing the \ from the string. I tried:

string.replace("\\", "")

But it doesn’t work. I’ve also tried converting to array and filtering out that way but no luck. Does anyone know how to do this?

:bust_in_silhouette: Reply From: flesk

You are on the right track, but strings are immutable, so to achieve what you want, you have to assign the result of the substitution to a variable:

string = string.replace("\\", "")

You don’t need a new variable though, since you can use your current variable to hold the new string.

EDIT: What you have is already json. You can convert it to a dictionary with the following code:

var dict = {}
var test_string = "{\"username\":\"Stubbsy345\"}"
dict.parse_json(test_string)
prints("username:", dict["username"])

Thanks for your reply, Unfortunately I have tried that and it doesn’t work. I’ll share some code.

var test_string = "{\"username\":\"Stubbsy345\"}"
test_string = test_string.replace("\\", "")
print(to_json(test_string))

test string will still equal:

"{\"username\":\"Stubbsy345\"}"

Trying to parse the test_string returns null as it can’t be parsed due to the \

stubbsy345 | 2017-11-18 20:21

What you have is already json, so what does your to_json() function do? If you’re trying to convert from json, see my updated answer.

flesk | 2017-11-18 21:08

Sorry, not sure I understand your code. When converted to a dictionary the string retains the backslashes and so does not format to a dictionary I don’t think. Your above code just produces an error saying dict does not have “username”.

I think the code you meant was:

var dict = {}
var dict = "{\"username\":\"Stubbsy345\"}"
prints("username:", dict["username"])

This also doesn’t work?

stubbsy345 | 2017-11-18 21:15

Sorry, I accidentally left out a vital piece of code. Try now.

flesk | 2017-11-18 21:23

Oh I get it. I didn’t really get that what I had was JSON in the string I thought I had to have it in a dictionary format and convert. Thanks for your help, working great now.

stubbsy345 | 2017-11-18 21:30

That’s an easy mistake. Glad I could help. :slight_smile:

flesk | 2017-11-18 21:33