I am very new to rails in general and what I have is a hash being passed as json for one format and now I need to pass it to the view to work with but I have no idea how to iterate over the hash to make it work in the view as I need to do some type of each loop over it. Its a 2 dimensional hash dunno if that means anything or not.
edit
example
{"status":"successful","service_list":[{"service_name":"mySQL","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"PHP","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"APache","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"Jetty","status":"RUNNING","status_message":"No errors reported","host":"1"}]}
This renders fine when I do it as JSON, but using the same thing to render it out in an HTML based view is where I am getting stuck
You have converted a Ruby has to a JSON hash, which is a Javascript format. In Ruby you would access a hash as follows:
hash = {"foo": "bar"}
puts hash["foo"] # This returns "bar"
JSON is similar to Ruby, and can be accessed in the same manner:
var hash = {"foo": "bar"};
alert(hash["foo"]); # This alerts "bar"
If you want to iterate through this collection in Javascript, you can use a for loop:
var data = {"status":"successful","service_list":[{"service_name":"mySQL","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"PHP","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"APache","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"Jetty","status":"RUNNING","status_message":"No errors reported","host":"1"}]};
for(x=0;x<data["service_list"].length;x++) {
alert(data["service_list"][x]["service_name"]); # This returns "mySQL", ...
};
If you are wanting to convert this JSON object to a Ruby has you can call "JSON.parse" with your JSON string as an argument.
Related
I am building a Rails 5.2 app.
In this app I am sending parameter from my Angular app to the server with a JSON.stringify object that looks like this when it arrives to the server:
"[{\"price\":\"silver\"},{\"price\":\"bronze\"}]"
I want to "unpack" it to look like a real JSON object again (because Stripe, that I will send this too only accept a JSON object:
[{"price":"silver"},{"price":"bronze"}]
If I run JSON.parse it only converts to a Hash which is not what I want.
If you want to operate or manipulate that JSON then you need to parse it to Hash.
JSON is treated as a string in ruby and you cannot operate properly on that so by parsing it to hash you can manipulate it using ruby also you can again change the resulting hash back to JSON string and as far as I've worked with Stripe it will work, so
For parsing JSON to Hash:
hash = JSON.parse(json_string)
For parsing Hash to JSON:
json_string = JSON.generate(hash)
or
json_string = hash.to_json
I have a Rails model in which one of the text fields contains a JSON string. While rendering it in views with JSON format (such as through index or show) I want to convert the string to a JSON hash. How can I do this with jbuilder or otherwise?
In general, how to apply a transform on a field by calling some function, before rendering it via jbuilder.
Of course, the naive solution is to build the JSON manually and use render json: my_json_here but I am looking for a better way.
Well a JSON is a string already... Maybe you want to convert it back to an object...
This will transform you string into a hash or array object.
JSON.parse(string)
If you want to make the other way around, transform you hash or array into a JSON string:
{ foo: 'bar' }.to_json # "{\"foo\":\"bar\"}"
EDIT: As you are looking for something more advanced, I recommend using the gem ActiveModelSerializer, where you create serializer objects that can be used to render ActiveModel data into any format, like JSON.
I think you could use "serialization" to do this where all of the conversion from JSON object to string and back is handled by ruby.
apidock
We have a caching layer that stores json output of strings. I'd like to be able to put these strings into an array which I then transform to json via .to_json but it escapes all the previously encoded json. Is there a way to avoid this?
Here's a sample action to explain:
def index
a={name:"jon", email:"jon#domain.com"}.to_json
r={}
r[:users]=[]
r[:users] << a
render json: r.to_json
end
Outputs:
{"users":["{\"name\":\"jon\",\"email\":\"jon#domain.com\"}"]}
But I want:
{"users":["{"name":"jon","email":"jon#domain.com"}"]}
Though I am not showing it here, I'd be open to using ActiveModelSerializer (the 0.8 branch)
Edit
One possibility is doing a JSON.parse but obviously, that's a bit of a performance hit which I'd like to avoid.
You are converting a json object to another json object.. Try replacing
a={name:"jon", email:"jon#domain.com"}.to_json
by
a={name:"jon", email:"jon#domain.com"}
I have a JSON block that I want to convert to a ruby hash.
json_blob = {"WHATEVER"=>{"FOO"=>"BAR", "CAT"=>"DAY}}
so that when I am using the data, I can check whether the data is there. Example:
hashed_json_blob[:whatever][:foo] returns "bar"
and also, I could handle values that don't exist either (they were omitted in the json_blob).
hashed_json_blob[:whatever][:nonexistant] returns nil
Note: if there is an easier way with the data as XML, that can work to. The json_blob was pulled using JSON.parse
your json_blob object is already a hash (minus one missing quote at the end of "DAY"):
json_blob = {"WHATEVER"=>{"FOO"=>"BAR", "CAT"=>"DAY"}}
with this you can do:
json_blob["WHATEVER"]
=> {"FOO"=>"BAR", "CAT"=>"DAY"}
json_blob["WHATEVER"]["FOO"]
=> "BAR"
The same data as a json object would look like this:
{"WHATEVER":{"FOO":"BAR","CAT":"DAY"}}
gem install json
require 'json'
json_blob = {"WHATEVER"=>{"FOO"=>"BAR", "CAT"=>"DAY}}
abc = JSON.parse(json_blob)
now you can perform operations on abc
I have a rails app which gets a response from World Weather Online API. I'm using the rest-client gem and the response is in JSON format.
I parse the response using:
parsed_response = JSON.parse(response)
Where parsed_response is obviously a hash.
The data I need are strings inside a hash inside an array inside a hash inside another array inside another hash inside another hash.
The inner-most nested hashes are inside ["hourly"], an array of 8 hashes, each with 20 keys, possessing string values of various weather parameters. Each of these hashes in the array is a different time of day (the forecast is three-hourly, 3*8 = 24hours).
So, for example, if I want the swell height in metres at 9pm, I find it with the following call:
#swell_height = parsed_data["data"]["weather"][0]["hourly"][7]["swellHeight_m"]
Where the 7th element in the array correspond to "time" => "2100"
While I can definitely work with this, I'm curious as to whether there is a more straightforward method of accessing my data, like if it was a database table, I could use active record, something like:
#swell_height = parsed_data.swellHeight_m.where(:time => "2100")
You may want to look at JSONPath. It does exactly what you need. Its syntax is very similar to XPath, but JSONPath works with JSON data (as obvious).
There is a Ruby implementation: https://github.com/joshbuddy/jsonpath
I personally use it in every project where I need to test JSON responses.