user1917603 user1917603 - 1 year ago 81
JSON Question

How to create a complex hash in ruby?

I'm building a rails app that is using ElasticSearch. What I'm trying to do is have the rails app send the client a JSON object with the ElasticSearch results. Where I could use help, is how to properly create the object that is sent to the web client.

Right now, in my rails controller, I'm creating a hash. Is hash the right way to go? Am I creating the hash correctly?

# Get the search results
@documents =[:q],

# Create the HASH
if @documents.count > 0
@documents.aggregations.by_authentication_id.buckets.each_with_index do |bucket, index|
# Create buckets
@json[ :buckets ][ index ] = {}
@json[ :buckets ][ index ][ :key ] = bucket["key"]
@json[ :buckets ][ index ][ :documents ] = {}
bucket["by_top_hit"].hits.hits.each_with_index do |d,i|
@json[ :buckets ][ index ][ :documents ][i] = {
title: d._source.document_title,
snippet: d.text

logger.debug @json

Am I creating the object correctly? I'm looking to learn how to do this right/optimally. I appreciate the advice, tips etc... Thank you

Answer Source

Not really sure what you are looking for but I think this structure might be nicer for you as a JSON object:

json = {}
json[:buckets] = do |bucket|

    key: bucket["key"],
    documents:  bucket["by_top_hit"] do |doc| 
                  { title: doc._source.document_title,
                    snippet: doc.text

This will produce a result that looks like

 {buckets: [
          {key: 'bucket_key',
           documents: [
                    {title: 'Some Title',
                     snippet: 'snippet'},
                    {title: 'Some Title2',
                     snippet: 'snippet2'}
           {key: 'bucket_key2',
           documents: [
                    {title: 'Some Title3',
                     snippet: 'snippet3'},
                    {title: 'Some Title4',
                     snippet: 'snippet4'}

Then you can just call .to_json on this Hash to get the json string for this object to be passed back.