string to json after getting value from redis ruby - ruby-on-rails

I created a simple json object something like this:
a = {"b": 1, "c": 2}
Setting the json object as value in redis like this:
LocalCache.set('abc', a)
After getting the value from redis, I am getting a string value:
x = LocalCache.get('abc')
I want this string to be converted back to JSON object but I am unable to do it.
When I tried x.as_json, I am getting "{:b=>1, :c=>2}"
When I tried x.to_json, I am getting "\"{:b=\\u003e1, :c=\\u003e2}\""
When I tried JSON.parse(x), I am getting this error:
JSON::ParserError: 785: unexpected token at '{:b=>1, :c=>2}'
Any help would be highly appreciated.

"{:b=>1, :c=>2}"
Is not valid json. It's a ruby hash. Cast it to json before cache-ing it and then parse it after you retrieve it.
LocalCache.set('abc', a.to_json)
x = LocalCache.get('abc')
JSON.parse(x)

From Redis documentation: https://github.com/redis/redis-rb#storing-objects
Redis stores only strings as values. You have to serialize the value you are setting to as json and then parse it back as JSON after retrieving.
a = {"b": 1, "c": 2}
Here a is object of class Hash. Hence serialize while storing
x = LocalCache.set("abc", a.to_json)
To retrieve: x = JSON.parse LocalCache.get('abc')
p x # {"b"=>1, "c"=>2}

Related

Rails params to array

I am sending a list of checkbox selected from PHP file to our Rails API server. All checked items' ID's will be sent in json format (campaign_ids in json_encode from PHP):
I got a URL being passed to our API like this
Started PUT "/campaigns/function.json?campaign_ids=["6","7"]&user_id=0090000007"
I need to get the campaign_ids ["6","7"] and process it like any other array using array.each do || end
How can I convert this to an array so I can use array.each?
The following sample code can achieve it but I think there could be a better way?
campaign_ids = params[:campaign_ids].to_s # [\"6\",\"7\"]
campaign_ids = campaign_ids.gsub(/[^0-9,]/,'') # 6,7
if campaign_ids.size.to_i > 0 # 3 ??
campaign_ids.split(",").each do |campaign_id|
...
end
end
The correct format of the URL should've been campaign_ids[]=6&campaign_ids[]=7. That would automatically yield an array of [6, 7] when you do params[:campaign_ids].
But assuming you can't change the format of the incorrect parameters, you can still get it via JSON.parse(params[:campaign_ids])
Try this
campaign_ids = JSON.parse(params[:campaign_ids])
You get params[:campaign_ids] as a string.
So, you will have to parse that json string to get array elements.
params[:campaign_ids] is already in your desired array format, you need not convert that to string using to_s.
You can do something like this
campaign_ids = params[:campaign_ids]
campaign_ids.each do |campaign_id|
# do the computation here
end

How can I use JSON data with Ruby?

This seems really simple but I've looked all over and I can't find any documentation for this.
I have the following json file:
//data.json
{
"movie1": [
{"name": "Inception"}
]}
and I just want to print the value of name with Ruby.
json = File.read('data.json')
data = JSON.parse(json)
data['movie1']['name']
But I'm getting the error
"no implicit conversoin of String into Integer"
How can I print name?
"no implicit conversion of String into Integer" usually comes when you're trying to use an array as a hash. Array[] expects an index (integer). Your data is a hash inside an array inside a hash :
You need :
data['movie1'][0]['name']
or
data.dig('movie1', 0, 'name')

Generation of table and accessing elements of a Array of Hashes

I have the following Array of hashes in a rails application:
a = ["{\"ROW1\"=>{\"correct\"=>{\"h\"=>\"10\", \"m\"=>\"11\", \"l\"=>
\"12\"}, \"wrong\"=>{\"h\"=>\"2\", \"m\"=>\"2\", \"l\"=>\"4\"}, \"blank
\"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"3\"}}, \"ROW2\"=>{\"correct
\"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"4\"}, \"wrong\"=>{\"h
\"=>\"4\", \"m\"=>\"6\", \"l\"=>\"6\"}, \"blank\"=>{\"h\"=>\"7\",
\"m\"=>\"5\", \"l\"=>\"6\"}}, \"ROW3\"=>{\"correct\"=>{\"h\"=>\"4\",
\"m\"=>\"6\", \"l\"=>\"7\"}, \"wrong\"=>{\"h\"=>\"6\", \"m\"=>\"7\",
\"l\"=>\"5\"}, \"blank\"=>{\"h\"=>\"7\", \"m\"=>\"9\", \"l\"=>
\"3\"}}}"]
I want to access its elements and create a database table from it, in the following format
ROW1 correct h=10, m=11,l=12
wrong h=2, m=2,l=4
blank h=2, m=4,l=3
...and similar for ROW2 and ROW3.
How can I do that?
I tried to access a value using
a["ROW1"]["Correct"]["h"]
...but it returns a nil value.
How to access the values of this array of hashes?
you need to first convert the string to hash which can be done as follows:
require 'json'
a = ["{\"ROW1\"=>{\"correct\"=>{\"h\"=>\"10\", \"m\"=>\"11\", \"l\"=>
\"12\"}, \"wrong\"=>{\"h\"=>\"2\", \"m\"=>\"2\", \"l\"=>\"4\"}, \"blank
\"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"3\"}}, \"ROW2\"=>{\"correct
\"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"4\"}, \"wrong\"=>{\"h
\"=>\"4\", \"m\"=>\"6\", \"l\"=>\"6\"}, \"blank\"=>{\"h\"=>\"7\",
\"m\"=>\"5\", \"l\"=>\"6\"}}, \"ROW3\"=>{\"correct\"=>{\"h\"=>\"4\",
\"m\"=>\"6\", \"l\"=>\"7\"}, \"wrong\"=>{\"h\"=>\"6\", \"m\"=>\"7\",
\"l\"=>\"5\"}, \"blank\"=>{\"h\"=>\"7\", \"m\"=>\"9\", \"l\"=>
\"3\"}}}"
]
hash_string = a[0]
hash = JSON.parse hash_string.gsub("\n", '').gsub('=>', ':')
# you access the hash now:
hash["ROW1"]["correct"]["h"]
# => 10
Btw, please note that there is a typo. Instead of Correct, the key is correct with small c instead of capital C.
Hope it helps : )

Ruby On Rails: Accessing Array?

I have an array stored in a variable temp which looks like this:
temp.inspect output :
[#"Marlana Letelier", "completed_at"=>nil, "status"=>"incomplete", "name"=>nil, "lead_move_date"=>"2012-06-17 00:00:00", "archive_time"=>nil, "stop_time"=>nil, "priority"=>"2", "assigned_to_user_firstname"=>"Vanessa", "notes"=>"", "created_by_id"=>nil, "id"=>"804005", "assigned_to_id"=>"1", "dn_email_id"=>nil, "outcomes_string"=>"other", "lead_id"=>"101139", "flavor"=>"PhonecallTask", "stringified_parameters"=>"{\n'purpose' => 'continued contact attempt',\n'phone_number' => '361-946-9905',\n}", "created_at"=>"2011-12-21 13:29:07", "start_time"=>"2012-04-04 17:00:00"}>]
temp.class specifies it as an array but temp[1] doesn't output anything.
How do I access the elements ?
EDIT:
1) Temp either had nothing, 1 object or multiple objects
2) Check for nil
3) Get each object out
4) access the attributes
Although your inspect output looks wrong (I think you're missing some text that came out in <...> tags) it looks like you have an array with a single item. Verify this assumption by outputting temp.length.
Since Arrays in Ruby are 0-indexed, try temp[0] or temp.first.

JSON string to rails hash

I'm on Rails 2.3 and I'm trying to convert a string that is JSON-formatted to a Rails hash. However, when I use JSON.parse I get a JSON string without the delimiters:
{"source_id":40007,"object":"86088947610496.1","coursewalk_id":"86088947610477.1","description":"","image_uri":"db\/db-files\/
Image_2011-09-24_14.37.37__0000.jpg","latitude":"38.0113439821061","letter":"","letter_A":"","letter_B":"","letter_C":"","lett
er_D":"","letter_E":"","letter_F":"","longitude":"-78.7576854509104","number":"1","mcw_id":71}
Results of JSON.parse:
number1letter_Bcoursewalk_id86088947610477.1letter_Clatitude38.0113439821061letter_Dletter_Eletter_Fmcw_id71longitude-78.75768
54509104letterdescriptionobject86088947610496.1source_id40007letter_Aimage_uridb/db-files/Image_2011-09-24_14.37.37__0000.jpg
Code:
puts string_to_parse
fence_parsed = JSON.parse(string_to_parse)
puts fence_parsed
Any ideas?
Thanks,
Nick
That's just because you're using "puts". If you just type fence_parsed, or p fence_parsed you'll get what you're looking for. puts calls to_s. I hope this clears it up for you, if not let me know and I'll elaborate.

Resources