Escape methods within single qoutes - ruby-on-rails

I am using the gmaps4rails gem and building my own markers json in my controller, but because it is in single qoutes it does not recognize my variables (#claim.longitude). Is it possible to escape the single qoutes, or is there another way to do this?
#markers = '[{"description": "", "title": "My Location: Seattle", "sidebar": "",
"lng": "#{#claim.longitude}", "lat": "#{#claim.latitude}",
"picture": "", "width": "", "height": ""}]'

Let Rails create the JSON for you.
> json_string = [{"foo" => "bar", "fred" => "barney"}].to_json
> puts json_string
[{"fred":"barney","foo":"bar"}]
If you get to the point where you want to convert your models into JSON, then look up the as_json method as well.

Related

Filter through nested JSON object and obtain JSON with specific keys, using Ruby

I currently have a nested JSON object which resembles
{
"People": [
{
"Name": "James",
"Age": "18",
"Gender": "Male",
"Sports": []
},
{
"Name": "Sarah",
"Age": "19",
"Gender": "Female",
"Sports": [
"Soccer",
"Basketball",
"Football"
]
}
]
}
Being new to Ruby, I aim to filter throught the entire json and return only the json object/objects in which the "Sports" array has content. So in the above scenario I expect to obtain the object below as a final outcome:
{
"Name": "Sarah",
"Age": "19",
"Gender": "Female",
"Sports": [
"Soccer",
"Basketball",
"Football"
]
}
Will I have to initiate a new method to perform such an act? Or would using regular ruby calls work in this case?
Although #philipyoo answer is right, it miss an explanation on how to "filter" the parsed JSON. If you are new to ruby, take a look at Array#keep_if : http://ruby-doc.org/core-2.2.0/Array.html#method-i-keep_if
require 'json'
people = JSON.parse("{long JSON data ... }")
people_with_sports = people.fetch('People', []).keep_if do |person|
!person.fetch('Sports', []).empty?
end
If you're getting a JSON object from a request, you want to parse it and then you can traverse the hash and arrays to find the information you need. See http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html
In your case, something like this:
require 'json'
parsed_json = JSON.parse('{"People": [ ... ]}')
parsed_json["People"].each do |person|
puts person if person["name"] == "Sarah"
end

Ruby/Rails - interate over complex (nested) JSON elements to create objects

I'm parsing some JSON from a mixed content source, and with it trying to store it with ActiveRecord.
At the moment I'm using a ton of variables:
json['settings']['newsletters']['weekly']
json['info']['address']['city']
Or trying to make things a little easier:
newsletters = json['settings']['newsletters']
newsletters['weekly']
address = json['info']['address']
address['city']
But this is all getting very messy, and not DRY.
I think the better way to do this would be to iterate over each element that is a hash (and therefore 'complex'), and assign it it's own object. This way, I don't have to declare a trillion variables, they can instead be assigned from the context of the JSON input.
So, I can do something like this:
user = json['input']
user.settings.newsletters.weekly
user.info.address.city
This is inspired by what ActiveResource documents:
# Any complex element (one that contains other elements) becomes its own object:
#
# {"id":1,"first":"Tyler","address":{"street":"Paper St.","state":"CA"}}
tyler = Person.find(1)
tyler.address # => <Person::Address::xxxxx>
tyler.address.street # => 'Paper St.'
Here is the JSON, reduced for brevity's sake:
{
"username": "robert_fitzsimmonds",
"emails": [{
"id_number": 1,
"address": "robert_fitzsimmonds#yahoo.com",
"confirmed": false
}, {
"id_number": 2,
"address": "robert_fitzsimmonds#gmail.com",
"confirmed": true
}],
"settings": {
"marketing": {
"main": true,
"weekly": false,
"daily": false
},
"language": "English"
},
"info": {
"address": {
"line_1": "31 Mole Road",
"line_2": "",
"city": "London",
"post_code": "NE4 5RJ"
},
"shared_account": false
}
}
Would such an iteration be the most efficient solution, or is it best to stick to long, messy variables?
Use the hash_dot gem if you can https://github.com/adsteel/hash_dot

Loop through nested hash in Rails controller

What I’m trying to do is loop through a hash and save certain key’s values to the database. This hash has nested keys, and I’m struggling to find a suitable way to loop through it.
First, I’m parsing the JSON of photos (from 500px API), and putting the response into terminal:
def index
#photos = JSON.parse(get_access_token.get('/v1/photos/search?term=california').body)
p #photos
save #photos
end
The response I get in console is all okay and looks like this. (I’ve cut it down so it doesn’t take up too much room):
{
"current_page": 1,
"total_pages": 50,
"total_items": 8263,
"photos": [
{
"id": 4930535,
"name": "Bike",
"description": "",
"times_viewed": 28,
"rating": 27,
"created_at": "2012-02-10T00:39:03-05:00"
},
{
"id": 4930206,
"name": "Rain",
"description": "",
"times_viewed": 1,
"rating": 59.7,
"created_at": "2012-02-10T00:04:09-05:00"
},
{
"id": 4930202,
"name": "California",
"description": "",
"times_viewed": 100,
"rating": 58.2,
"created_at": "2012-02-10T00:05:25-05:00"
}
]
}
I’m then trying to loop through the photos and save the name, description and times_viewed to the db, using this save method.
def save photos
photos.each do |photo|
p = Photo.new(:name => photo["photos"]["name"], :description => photo["photos"]["description"], :times_viewed => photo["photos"]["times_viewed"])
p.save
end
end
The trouble is that the photos key is nested, and it throws this error in terminal:
TypeError (no implicit conversion of String into Integer):
app/controllers/photos_controller.rb:18:in `[]'
app/controllers/photos_controller.rb:18:in `block in save'
app/controllers/photos_controller.rb:17:in `each'
app/controllers/photos_controller.rb:17:in `save'
app/controllers/photos_controller.rb:10:in `index'
Just take the photos array out of your json response and iterate over that. This way you only have one layer of hash keys to reference:
json_response['photos'].each do |photo|
Photo.create name: photo['name'], description: photo['description'],
times_viewed: photo['times_viewed']
end
photos["photos"] is an array so you need to specify the index before name. The implementation of your save method isn't completely clear, but I believe your parameters for the new method should have the form:
:name => photo["photos"][index]["name"]
You're getting a conversion error since the compiler is trying to convert name into an index.

Extract specific field from JSON nested hashes

I am thinking of writing a web application that crawls an API and returns this information in JSON form.
However, I am only after one number, then current price (in this sample, "227"). How can I access that in Ruby? I have no clue where to begin. I've never dealt with text like this.
For discussion's sake, suppose I save this output into instance variable #information
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_rs/4332_obj_sprite.gif?id=4798",
"icon_large": "http://services.runescape.com/m=itemdb_rs/4332_obj_big.gif?id=4798",
"id": 4798,
"type": "Ammo",
"typeIcon": "http://www.runescape.com/img/categories/Ammo",
"name": "Adamant brutal",
"description": "Blunt adamantite arrow...ouch",
"current": {
"trend": "neutral",
"price": 227
},
"today": {
"trend": "neutral",
"price": 0
},
"day30": {
"trend": "positive",
"change": "+1.0%"
},
"day90": {
"trend": "positive",
"change": "+1.0%"
},
"day180": {
"trend": "positive",
"change": "+2.0%"
},
"members": "true"
}
}
First follow this post to parse this JSON in to Hash
Parsing a JSON string in Ruby
say the parsed hash name is my_hash then the following should give you price
my_hash['item']['current']['price']
Edit:
As you said you want to save it in #information
#information = my_hash['item']['current']['price']
Even you can use hashie it gives your json into readable structural code
Install Hashie
gem install hashie
then in your code all that json take in a variable my_json
myhash = Hashie::Mash.new(my_json)
#information = my_hash.item.current.price
Tips:-
if your json is dynamic and it may respond some other structural element so you can maintain exceptional code
#information = my_hash.item.try(:current).try(:price)

How do I pretty print a hash to a Rails view?

I have something like:
{"a":"1","b":"2","c":"3","asefw":"dfsef"}
I want to print it out in a view. What's the best way to do that?
I tried parsing it as a JSON object and using JSON.stringify, but it seems to mess up indentation.
Any advice? I don't mind a JavaScript solution.
How about:
require 'json'
hash = JSON['{"a":"1","b":"2","c":"3","asefw":"dfsef"}']
puts JSON.pretty_generate(hash)
Which outputs:
{
"a": "1",
"b": "2",
"c": "3",
"asefw": "dfsef"
}
JSON.pretty_generate is more of a debugging tool than something I'd rely on when actually generating JSON to be sent to a browser. The "pretty" aspect also means "bloated" and "slower" because of the added whitespace, but it is good for diagnosing and comprehending what is in the structure so it might work well for your needs.
One thing to remember is that HTML, when rendered by a browser, has whitespace gobbled up, so whitespace runs disappear. To avoid that you have to wrap the JSON output in a <pre> block to preserve the whitespace and line-breaks. Something like this should work:
<pre>
{
"a": "1",
"b": "2",
"c": "3",
"asefw": "dfsef"
}
</pre>
irb(main)> puts queried_object.pretty_inspect
From PrettyPrint, so may need to require 'pp' first for this to work.
This also works great for e.g. Rails.logger output.
<%= raw JSON.pretty_generate(hash).gsub(" "," ") %>
If you (like I) find that the pretty_generate option built into Ruby's JSON library is not "pretty" enough, I recommend my own NeatJSON gem for your formatting.
To use it gem install neatjson and then use JSON.neat_generate instead of JSON.pretty_generate.
Like Ruby's pp it will keep objects and arrays on one line when they fit, but wrap to multiple as needed. For example:
{
"navigation.createroute.poi":[
{"text":"Lay in a course to the Hilton","params":{"poi":"Hilton"}},
{"text":"Take me to the airport","params":{"poi":"airport"}},
{"text":"Let's go to IHOP","params":{"poi":"IHOP"}},
{"text":"Show me how to get to The Med","params":{"poi":"The Med"}},
{"text":"Create a route to Arby's","params":{"poi":"Arby's"}},
{
"text":"Go to the Hilton by the Airport",
"params":{"poi":"Hilton","location":"Airport"}
},
{
"text":"Take me to the Fry's in Fresno",
"params":{"poi":"Fry's","location":"Fresno"}
}
],
"navigation.eta":[
{"text":"When will we get there?"},
{"text":"When will I arrive?"},
{"text":"What time will I get to the destination?"},
{"text":"What time will I reach the destination?"},
{"text":"What time will it be when I arrive?"}
]
}
It also supports a variety of formatting options to further customize your output. For example, how many spaces before/after colons? Before/after commas? Inside the brackets of arrays and objects? Do you want to sort the keys of your object? Do you want the colons to all be lined up?
For example, using your example Hash, you can get these different outputs, depending on what you want:
// JSON.neat_generate(o, wrap:true)
{
"a":"1",
"b":"2",
"c":"3",
"asefw":"dfsef"
}
// JSON.neat_generate o, wrap:true, aligned:true
{
"a" :"1",
"b" :"2",
"c" :"3",
"asefw":"dfsef"
}
// JSON.neat_generate o, wrap:true, aligned:true, around_colon:1
{
"a" : "1",
"b" : "2",
"c" : "3",
"asefw" : "dfsef"
}
You can try the gem awesome_print works very well, and in your view write
<%= ap(your_hash, plain: true, indent: 0).html_safe %>
also, you can change the values for config the styles to hash view
The given response is works fine, but if you want to have prettier and more custom pretty hash, use awesome_print
require 'awesome_print'
hash = JSON['{"a":"1","b":"2","c":"3","asefw":"dfsef"}']
ap hash
Cheers!
Pretty Print Hash using pure Ruby (no gems)
I came across this thread trying to solve this problem for myself.
I had a large Hash that I wanted to make pretty, but I needed to stay in ruby hash notation instead of JSON.
This is the code + examples
Use pretty_generate to get a nice formatted JSON string.
Replace all the JSON keys with symbol: equivalent
puts JSON.pretty_generate(result)
.gsub(/(?:\"|\')(?<key>[^"]*)(?:\"|\')(?=:)(?:\:)/) { |_|
"#{Regexp.last_match(:key)}:"
}
Sample JSON
{
"extensions": {
"heading": "extensions",
"take": "all",
"array_columns": [
"name"
]
},
"tables": {
"heading": "tables",
"take": "all",
"array_columns": [
"name"
]
},
"foreign_keys": {
"heading": "foreign_keys",
"take": "all",
"array_columns": [
"name"
]
},
"all_indexes": {
"heading": "all_indexes",
"take": "all",
"array_columns": [
"name"
]
},
"keys": {
"heading": "keys",
"take": "all",
"array_columns": [
"name"
]
}
}
Sample Ruby Hash
{
extensions: {
heading: "extensions",
take: "all",
array_columns: [
"name"
]
},
tables: {
heading: "tables",
take: "all",
array_columns: [
"name"
]
},
foreign_keys: {
heading: "foreign_keys",
take: "all",
array_columns: [
"name"
]
},
all_indexes: {
heading: "all_indexes",
take: "all",
array_columns: [
"name"
]
},
keys: {
heading: "keys",
take: "all",
array_columns: [
"name"
]
}
}

Resources