0

I have a string like this:

"[\"fr\", \"sv\"]" 

and I want to convert this string into an array like following.

["fr", "sv"] 

I tried too many thing but not getting the expected outcome. Can anyone help?

1
  • 1
    The string is valid JSON. Is that always guaranteed? Where does it come from? Can you modify the source to make sure that it is always valid JSON? Commented Mar 30, 2019 at 12:46

2 Answers 2

5

"[\"fr\", \"sv\"]" - This is JSON-string array.

You should parse string as json:

require 'json' # => true JSON.parse("[\"fr\", \"sv\"]") # => ["fr", "sv"] 

Reverse process:

require 'json' # => true ["fr", "sv"].to_json # => "[\"fr\",\"sv\"]" 
Sign up to request clarification or add additional context in comments.

Comments

3

Your string looks like JSON, therefore I would use a JSON parser:

require 'json' string = "[\"fr\", \"sv\"]" JSON.parse(string) #=> ["fr", "sv"] 

1 Comment

Your answer was a little earlier.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.