Trying to extract key value from parsed JSON in ruby - ruby

I’m trying to parse some JSON from the twitter API and extract the value of a key (“media_url”), which is a sub-key of the key (“entities”)
so far I have:
url = 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&screen_name=print_broadcast&count=1'
response = RestClient.get(url)
data=response.body
result = JSON.parse(data)
How would I extract a key value from the parsed JSON?
I’ve tried
result[“entities”]
etc, but I get en error when trying to convert a string to integer... the result of my parsed JSON is an array - shouldn't this be a hash?
Sorry for the dumb questions.
Any help would be appreciated.

The JSON output is actually a list. Granted, it only has one element, but it's still a list.
First get result[0], then you can access ['entries'].

Related

how do I parse out this URL-encoded string with a JSON array using Ruby?

When I use a webhook with Mandrill and post to my Iron Worker, I get the following Raw (this is from RequestBin, as well) -- I didn't include the whole payload, just an example:
puts payload =>
mandrill_events=%5B%7B%22event%22%3A%22inbound%22%2C%22msg%22%3A%7B%22dkim%22%3A%7B%22signed%22%3Atrue%2C%22valid%22%3Atrue%7D%2C%22email%22%3A%22kaya%40hellokaya.com%22%2C%22from_email%22%3A%22example.sender%40mandrillapp.com%22%2C%22headers%22%3A%7B%22Content-Type%22%3A%22multipart%5C%2Falternative%3B+boundary%3D%5C%22_av-7r7zDhHxVEAo2yMWasfuFw%5C%22%22%2C%22Date%22%3A%22Fri%2C+10+May+2013+19%3A28%3A20+%2B0000%22%2C%22Dkim-Signature%22%3A%5B%22v%3D1%3B+a%3Drsa-
I tried to extract the value of the parameter mandrill_events using:
puts params = CGI::parse(#payload) =>
{"mandrill_events"=>["[{\"event\":\"inbound\",\"msg\":{\"dkim\":{\"signed\":true,\"valid\":true},\"email\":\"kaya#hellokaya.com\",\"from_email\":\"example.sender#mandrillapp.com\",\"headers\":{\"Content-Type\":\"multipart\\/alternative; boundary=\\\"_av-7r7zDhHxVEAo2yMWasfuFw\\\"\",\"Date\":\"Fri, 10 May 2013 19:28:20 +0000\",\"Dkim-Signature\":[\"v=1; a=rsa-sha1; c=relaxed\\/relaxed; s=mandrill; d=mail115.us4.mandrillapp.com; h=From:Sender:Subject:List-Unsubscribe:To:Message-Id:Date:MIME-Version:Content-Type; i=example.sender#mail115.us4.mandrillapp.com;
Then I am stuck. I want to extract the email value in the JSON.array.
I thought to try the following;
puts json_params = JSON.parse(params)
But I am now feeling there must be a better way....
How can I extract the elements from the JSON array in this URL-encoded string?

parse out JSON.parse(cookies[:cookie_name]) item into ruby variable

I need to access a specific string inside the cookie.
I am using:
#id = JSON.parse(cookies[:cookie_name])
and it returns a JSON object. What is the best way to access a specific item in the JSON object?
Here is example of the JSON object:
{"distinct_id"=>"12345", "$initial_referrer"=>"$direct", "$initial_referring_domain"=>"$direct", "__mps"=>{}, "__mpso"=>{}, "__mpa"=>{}, "__mpap"=>[], "mp_name_tag"=>"12345", "id"=>"12345"}
What I want from that object is the distinct_id.
Any direction would be great.
That looks more like a Ruby hash than a JSON object (JSON.parse returns a hash as well). If that's the case, wouldn't #id['distinct_id'] work?

Can't convert string to integer ruby error when accessing Hash/Array

I am new to ruby. So I was trying to get data from my data array but I get a "can't convert String into Integer" error.
The way I am accessing data is
data["myobject"]
It seem that data is an array, not a hash.
I think data looks like this :
data=['foo', 'bar']
instead of looking like this :
data={'myObject'=>'foo', 'myObject2'=>'bar'}
So try to change data or retrieve data by its index
data[0]

Issue on parsing string at JSON.parse

In controller side i am getting params like
"{\"violation_date\":\"sdfsdf\",\"violation_time\":\"\"},{\"violation_date\":\"sdfdsf\",\"violation_time\":\"sdfsdf\"},{\"violation_date\":\"1233\",\"violation_
time\":\"\"},{\"violation_date\":\"test\",\"violation_time\":\"time\"}"
class of this is String. I am trying to parse this. Through
JSON.parse(params_gotton)
Got
JSON::ParserError (757: unexpected token at ',{"violation_date":"sdfdsf","violation_time":"sdfsdf"},{"violation_date":"1233","violation_time":""},{"violation_d
te":"test","violation_time":"time"}'):
What i am doing wrong here. Any suggestions?
It's not valid json, this will work (use []):
require 'json'
jsn = '[{"violation_date":"sdfsdf","violation_time":""},
{"violation_date":"sdfdsf","violation_time":"sdfsdf"},
{"violation_date":"1233","violation_time":""},
{"violation_date":"test","violation_time":"time"}]'
JSON.parse(jsn) # => [{"violation_date"=>"sdfsdf", "violation_time"=>""}, {"violation_date"=>"sdfdsf", "violation_time"=>"sdfsdf"}, {"violation_date"=>"1233", "violation_time"=>""}, {"violation_date"=>"test", "violation_time"=>"time"}]
To verify json string you could use: http://www.jslint.com/.
And basic json structure: http://json.org/
UPDATED
In your case just try this:
JSON.parse('[' + params_gotton + ']')
well, received string does not contain a proper Json structure..
First convert that received param in a proper json structure and then parse it using "JSON.parse(params_gotton)".
In above received data all key and value shud be in a key value pair string format.. remove "\" symbol from received data..
it will definitely work fine..

How do I extract a value from a JSON response?

I am writing some tests in Ruby using RestClient. The test is working fine and the response is in JSON however when I parse the JSON and try to extract the values I am looking for I get an error saying IndexError: key not found
IMO, my code should work. The JSON is:
{"user":{"#xmlns":{"dvi":"http:\/\/xxxx","a":"http:\/\/xxxx","$":"http:\/\/xxxx"},"link":[{"#rel":"self","$":"http:\/\/xxxx"},{"#rel":"user","$":"http:\/\/xxxx"},{"#rel":"usage","$":"xxxx"},{"#rel":"repositories","$":"http:\/\/xxxx"},{"#rel":"shares","$":"http:\/\/xxxx"},{"#rel":"shareMemberships","$":"http:\/\/xxxx"}],"phone":{"$":"3518012343001"},"email":{"$":""},"firstName":{"$":"Jim"},"lastName":{"$":"Joe"},"uid":{"$":"91bc7a72bc724e5e9b53e688dd105ed4"},"accountName":{"$":"3518012343001"},"notificationMethod":{"$":"email sms"},"accountStatus":{"$":"Active"},"serviceLevel":{"$":"5"},"repositoryCount":{"$":"1"},"usage":{"allowed":{"$":"5368709120"},"total":{"$":"1024"}},"contactEmail":{"$":"jim#joe.com"}}}
and my code is:
result = jsonabove
jdoc = JSON.parse(result)
notificationMethod = jdoc.fetch("notificationMethod")
return notificationMethod
That's happening because the notificationMethod key isn't the first level key in your hash. After preparing theJSON#parse method, you have a hash with only one key called user. You should get the value by this key and then apply your notificationMethod key. It looks like this:
require 'json'
result = <<HERE
{"user":{"......"}}
HERE
jdoc = JSON.parse(result)
notificationMethod = jdoc.fetch("user").fetch("notificationMethod")
puts notificationMethod

Resources