0

I would like to convert the following string into an array/nested array and iterate through it, so that i could use values from it.

 str = "[[{"one": "1"}],[{"two": "2"}],[{"three": "3"}]]"

// I want to use value inside the {} brace 
1
  • data = JSON.parse(str) // You might need to add the "gem 'json'" to the Gemfile first. Commented Jun 20, 2012 at 10:44

1 Answer 1

2

That is JSON(*), and can be parsed as JSON.

require 'json'
data = JSON.parse(str)

And then you can use the usual Array#each or Hash#each iterators.

*) Or at least it would be JSON, if it wasn't a syntax error. You can't have an unescaped double quote inside double quotes.

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

2 Comments

Thanks. with that i am getting {"one": "1"} and {"two": "2"} in for each loop. but when in loop i m trying to get ele["one"] or ele["two"] getting error like - TypeError (can't convert String into Integer):
Note that each hash in your data is wrapped in another array. The structure is Array of Arrays of Hashes. You would need ele[0]["one"] to get to the "1", or onion together two each loops (one for the outer Array, one for the inner Array).

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.