How can I parse string(ruby hash) to JSON or Array in Rhodes?

853 Views Asked by At

I have a mobile application that makes a request to my Rails backend.

The backend JSON returns the information in the following manner:

def get_data
    respond_to do |format|
      format.json{
        data = Form.select('column1, column2').where(field:'Rhodes')
        render :json => data
      }
    end
end

In my application (Rhodes), I'm using Rho::AsyncHttp.post and send to my webview index the data:

response = Rho::AsyncHttp.post(
        :url => 'http://xyx.xyx.x.yx:3000/data/get_data.json',
        :headers => {"Content-Type" => "application/json; charset=utf-8", "Accept" => "application/json"}
      )


WebView.navigate( url_for :action => :index , :query => { :form => response['body'] })

Now, when I inspect the variable form in my webview I get the data in the following structure:

<%= @form.inspect %>

"[{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"},{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"},{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"}]"

So, I need to show this data in a Table and I want loop this. I tried with each:

<h2>Data</h2>
<% @form.each do |x| %>
<div><%= x.tipo %></div>
<% end %>

But I get the error: undefined method each for #.

So, I tried to convert it to a JSON object:

data = Rho::JSON.parse(@form)

But, I get the following error:

JSON error code: 10; Ofset: 9
Trace:
(eval):36:in ´parse´
(eval):36:in '´
lib/rho/render.rb:175:in ´eval_compiled_file´
lib/rho/render.rb:175:in ´render´ [...]

I'm using Ruby 1.9.3 with Rhodes 3.5.1.12

UPDATE

I fix the problem with the function eval. Now I can loop the string. But when I try to print the variable. These not show.

<% data = eval(@form) %>
<% data.each do |hash| %>
 <ul>
   <li><%= puts hash['campo'] %></li> #only display the bullets but no the data
   <li><%= puts hash['tipo'] %></li> #only display the bullets but no the data
 </ul>
 <br />
<% end %>
1

There are 1 best solutions below

3
On

I don't use Rhodes, but...

You can't use JSON on this string:

"[{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"},{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"},{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"}]"

because it isn't a JSON serialized object. The => are the giveaway. JSON serializes hashes using : to delimit the key/value pairs.

Using inspect is probably confusing you because it will turn what looks like an array of hashes into a pseudo-string. I suspect it's really this:

ary = [{"campo"=>"nombre","tipo"=>"textfield"},{"campo"=>"nombre","tipo"=>"textfield"},{"campo"=>"nombre","tipo"=>"textfield"}]

because if I inspect ary I get:

# => "[{\"campo\"=>\"nombre\", \"tipo\"=>\"textfield\"}, {\"campo\"=>\"nombre\", \"tipo\"=>\"textfield\"}, {\"campo\"=>\"nombre\", \"tipo\"=>\"textfield\"}]"

This is how to iterate over the array of hashes:

ary.each do |hash|
  puts hash['tipo']
end
# >> textfield
# >> textfield
# >> textfield