1

How do I turn a string that resembles an array into an actual array? This thread advised that I should use JSON.parse -- Convert string into Array in rails, but when I go to try that, I get an error

localhost:nightminer satishp$ rails console
Running via Spring preloader in process 9674
Loading development environment (Rails 5.0.6)
irb(main):001:0> JSON.parse("['2de33']")
JSON::ParserError: 409: unexpected token at ''2de33']'
    from /usr/local/Cellar/ruby/2.4.2_1/lib/ruby/2.4./json/common.rb:156:in `parse'
    from /usr/local/Cellar/ruby/2.4.2_1/lib/ruby/2.4./json/common.rb:156:in `parse'
    from (irb):1

Any advice on how to get my array of strings is appreciated. Note I can't change the input (I can't remove the single quotes).

3
  • Where did you get this string? Just because it looks sort of like JSON doesn't mean it is JSON or that JSON.parse is the right tool for the job. Commented Mar 9, 2018 at 22:42
  • JSON doesn't allow single quotes to mark data? Commented Mar 9, 2018 at 22:49
  • 1
    No it doesn't, mrzasa has a link to the JSON standard in their answer. JSON is similar to JavaScript but they're not the same thing. Commented Mar 9, 2018 at 22:57

1 Answer 1

3

Single quotes ' are not valid string delimiters in JSON. You need to replace them with double quotes, e.g.:

JSON.parse("['de33']".gsub("'", "\""))
# => ["de33"] 

JSON standard says:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.