Emmanu
Emmanu

Reputation: 797

How to convert an array expressed in string form to actual array

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?

Upvotes: 0

Views: 121

Answers (2)

Kshitij
Kshitij

Reputation: 339

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.

Upvotes: -1

Cary Swoveland
Cary Swoveland

Reputation: 110665

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."

Upvotes: 5

Related Questions