+2 votes

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?

in Engine by (290 points)

1 Answer

+3 votes
Best answer

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"])
by (148 points)
selected by

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 \

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.

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?

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

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.

That's an easy mistake. Glad I could help. :)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.