1

I have the following array:

["{\"id\":1,\"name\":\"A\"}", "{\"id\":20,\"name\":\"B\"}"]

I get this array from redis and I need to iterate and access id and name keys. I really need to call JSON.parse in every iteration ?

How can I iterate and display data ?

7
  • 1
    "I really need to call JSON.parse in every iteration?" - on every element, yes. Commented Feb 16, 2018 at 13:24
  • like this? <% visitors.each do |v| %> <% visitor = JSON.parse(v) %> Commented Feb 16, 2018 at 13:26
  • This is one way to do this, yes. I'd prefer to not bloat my views with unnecessary logic, and move data preparation elsewhere (controller, for example) Commented Feb 16, 2018 at 13:27
  • 2
    yes I did this on a cell: def visitors @options[:visitors].map { |visitor| JSON.parse(visitor) } end Commented Feb 16, 2018 at 13:31
  • "I get this array from redis" – how is it stored in Redis, as a list? Commented Feb 16, 2018 at 14:11

2 Answers 2

1

First, nothing wrong with a loop:

arr = ["{\"id\":1,\"name\":\"A\"}", "{\"id\":20,\"name\":\"B\"}"]
arr.map {|raw| JSON.parse(raw) }

Now, if for any reason you want to avoid the loop, here is some fun option:

arr = ["{\"id\":1,\"name\":\"A\"}", "{\"id\":20,\"name\":\"B\"}"]
JSON.parse "[#{arr.join(",")}]"

So: join the array with ",", making a string that we put between "[]" - this transform your list of JSON encoded values into a single JSON encoded array.

This being said, again - nothing wrong with a loop.

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

3 Comments

good solution Martin, tried that but without the surrounding [] it failed
Just tried the code in my IRB with your exact example, looks to work:
iaa you misunderstood, your example works +1 (otherwise wouldn't be good :), I tried it the same way and it failed because of..
0

On your question if you need to do this with a map method you got the answer allready in the comments and the alternative from Martin.

Here is a way to separate the logic from your view like Sergio suggests

Somewhere in your controller, model or helper file

class Visitor
  require 'json'
  def initialize string
    hash = JSON.parse(string)
    @id   = hash["id"]
    @name = hash["name"]
  end

  def to_s
    "#{@id}: #{@name}"
  end
end

class Visitors
  include Enumerable

  @@visitors = []
  def initialize array
    array.map{|visitor| @@visitors << Visitor.new(visitor)}
  end

  def each
    @@visitors.map{|visitor| yield visitor}
  end
end


array = ["{\"id\":1,\"name\":\"A\"}", "{\"id\":20,\"name\":\"B\"}"]
visitors =  Visitors.new(array)

And in your view

visitors.each do |visitor|
  <%=visitor%>
end

# 1: A
# 20: B

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.