0

I have an array that is in string form

"[{"img_type":"HA","img_size":0,"img_name":"8a040ff1-e780-4843-9f01-6dc37e11f3c8"},{"img_type":"HB","img_size":0,"img_name":"8a040ff1-e780-4843-9f01-6dc37e11f3c8"}]"

I need to convert that to

[
  {"img_type": "HA", "img_size": 0, "img_name": "8a040ff1-e780-4843-9f01-6dc37e11f3c8"}, 
  {"img_type": "HB", "img_size": 0, "img_name": "8a040ff1-e780-4843-9f01-6dc37e11f3c8"}
]

I tried removing double quotes, but it didn't work. How can I convert this to an array?

9
  • 1
    you can try eval Commented Jul 27, 2018 at 5:28
  • Start by replacing the surrounding double quotes with single quotes. Commented Jul 27, 2018 at 5:36
  • 1
    @uzaif WUT? please never ever suggest such a weird stupid solutions for what can be done properly. Commented Jul 27, 2018 at 5:39
  • 2
    @mudasobwa, after posting I noticed that the OP wants the keys to be symbols rather than strings. I fixed it and undeleted. Commented Jul 27, 2018 at 5:45
  • 2
    you can do something like JSON.parse(str).map(&:symbolize_keys) in Rails Commented Jul 27, 2018 at 6:13

2 Answers 2

5
str = '[{"img_type":"HA","img_size":0,"img_name":"8a040ff1-e780-4843-9f01-6dc37e11f3c8"},{"img_type":"HB","img_size":0,"img_name":"8a040ff1-e780-4843-9f01-6dc37e11f3c8"}]'

require 'json'
JSON.parse(str, symbolize_names: true)
  #=> [{:img_type=>"HA", :img_size=>0, :img_name=>"8a040ff1-e780-4843-9f01-6dc37e11f3c8"},
  #    {:img_type=>"HB", :img_size=>0, :img_name=>"8a040ff1-e780-4843-9f01-6dc37e11f3c8"}]

Notice that JSON::parse provides for several optional parameters, one of which (symbolize_names) "returns symbols for the names (keys) in a JSON object. Otherwise strings are returned."

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

2 Comments

ruby-doc.org/core-2.5.1/Hash.html#method-i-transform_keysJSON.parse(str).map { |g| g.transform_keys(&:to_sym) }.
@mudasobwa, since posting I discovered that JSON#parse takes an optional parameter :symbolize_names, which appears to be just what is needed. Thought you might like to know.
-1

Try this,

str = '[{"img_type":"HA","img_size":0,"img_name":"8a040ff1-e780-4843-9f01-6dc37e11f3c8"},{"img_type":"HB","img_size":0,"img_name":"8a040ff1-e780-4843-9f01-6dc37e11f3c8"}]'
array = eval(str)

This may solve your purpose but its nasty to use eval as it brings serious danger of undefined methods and SQL injection.

Prefer JSON.parse(your_string)for this purpose.

2 Comments

Downvoted because, while it does produce the correct result, it does not mention the serious dangers of using eval.
Thanks @Max, I've added the some drawbacks of using eval.

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.