Filtering the result of a JSON.parse response in Ruby (and the JSON gem) - ruby

In a little app I'm building, I'm using the the twitter_oauth gem (source of the methods I'm using), which incidentally means I'm dealing with the JSON ruby gem.
I'm using the messages method, whose source is as follows:
def messages(page=1)
oauth_response = access_token.get("/direct_messages.json?page=#{page}")
JSON.parse(oauth_response.body)
end
It parses the JSON produced by Twitter, using the JSON.parse method. Now, what I want to do is filter the response, so as to show only the messages sent by a certain user. In other words, I want to be able to get an accounts message's on a per user basis.
I went through the JSON gem docs, but couldn't find an easy way to do this. I normally don't work with JSON (I prefer XML), but since the Twitter_oauth gem relies on it, I'm forced to learn it (unless I change the gem's source code or overwrite it - not of my preference).
Does any one know a pragmatic way of sorting JSON in Ruby?

Why do you have to work with JSON at all? JSON.parse gives you back deserialized structures (Ruby arrays and hashes), so all you have to do (I presume, you haven't pasted sample JSON output here) is to do select on whatever output JSON.parse (or, in your case, messages) method returns.

Related

Reading a JSON response from FireFox console

I have tried searching a bit for an answer but am having trouble, as I think this scenario is a little 'unique' in that the JSON file is coming from a server response after calling a method.
When you input example.Server.method() into the FireFox console manually, you get a JSON response. I want to input this into the console in a ruby script with selenium webdriver, so I can read an important piece of information from the JSON response.
I'm thinking I can call the method like so:
console.log("example.Server.method()")
But where does the JSON response actually 'go', since I want my script to find and parse the information? Calling the method results in a examplename.json file that I need to parse.
You could execute the java script like so
information = driver.execute_script("return example.Server.method()")

AJAX, JQuery, Parse - which one will get me my array?

In my codeacademy and codeschool lessons, I've been fetching data from google rss and simulated twitter feeds.
My newest exercise, however, involves fetching an array of text data from a REST API.
When I try
$.get('https://api.parse.com/1/classes/chats?order=-createdAt', function(x){$('.messages').append('<li>'+x.responseText+'</li>');});
I get
which has the text and username I need. Sort of...
but when I try to alert or console.log either *x.responseText or x.responseText.results I obviously get undefined instead of an array.
What am I missing?
Study more AJAX and I'll find a technique?
Or do I have to send special instructions to the parse server using some commands found here.
You are not using XMLHttpRequest directly, you are using jQuery and it will read the responseText and handle it for you.
Just use x (or, rather, x.results).

Check if a favorited tweet contains a URL within the body

Building a small app and would like to return all a users favorited tweets. This is easy enough to do with the twitter gem. I would then like to further filter the returned results by only displaying the favorited tweets that contain a URL within the body.
Now as I understand it Using the the twitter gem running Twitter.favorites will return a json of all the favorited tweets. Now within each of the individual tweets it returns a entity property that contains a URL hash this will be empty if no URL is present in the tweet and a URL if one is present.
How would I implement a check to say if the URL is present then display tweet. I'm a noob with json and Apis.
I never used the twitter gem, but since the question remains unanswered for a couple of hours, I’ll try to do my best.
First of all the gem seems to return Array<Twitter::Tweet> rather than raw json. So you only need to filter the array:
favs_with_urls = Twitter.favorites.reject { |r| r.urls.empty }
The latter should do the trick.
BTW, if you for some reason need to parse json to a hash:
require 'json'
c = JSON.load(raw_json)

Obtain XML element's value from REST server response using Ruby

n00b REST question. I'm making a GET request to an API's endpoint and getting the proper XML response. The question I have is, how do I get the value of a particular XML element in the servers REST response using Ruby?
So let's say one of the elements is 'Body' and I want to assign its value 'Blah blah blah' to a variable
Part of the XML response:
<Body>Blah blah blah</Body>
How would I do that with the response? Basically I want to do something like this
variable = params["Body"]
Thanks in advance!
The best solution is to use RestClient or HTTParty and have it parse the response for you.
Otherwise, you'll have to parse the response itself using a library such as Nokogiri:
doc = Nokogiri.XML(response)
variable = doc.at("body").text
You'll want to use an XML parser of some kind.
It sounds like you want something like XmlSimple, which will turn an XML document into ruby arrays and hashes. There's tons of examples of how to use it on the page that has been linked.
One thing to be aware of is that XML to native container mappings are imperfect. If you're dealing with a complex document, you'll likely want to use a more robust parser, like Nokogiri.
If you want full XML Object Mapping, HappyMapper is a decent library, although it isn't very active anymore. It can work with XML from any source, so you'll still want something like the libraries mentioned by #Fitzsimmons or #MarkThomas to do the HTTP request.

Parse JSON from Jenkins, once hash, then nil

Jenkins gives me JSON from http://jenkins.net/jobs/MyJob/lastBuild/api/json
Then I use HTTParty to get it like so:
response = self.get( url, options )
change = response['changeSet']['items'][0]
This gives me the content of the last changes. change.class returns "Hash".
If I try this:
change = response['changeSet']['items'][0]['revision']
as looking at the JSON suggests, I get "Undefined method '[]' on NilObject".
What am I doing wrong?
EDIT3:
Of course, the problem lies between User and keyboard. The method was first called on another JSON, because it's polling the changes for more than one project, and one of the returned JSON objects didn't contain those keys. D'oh!
Sorry.
If you get that kind of error you're hitting an empty key and then trying to use it as if it's populated. Without seeing what your JSON is, it's hard to say, but one of those is failing. You'll want to inspect these:
response['changeSet']
response['changeSet']['items']
response['changeSet']['items'][0]
If any of those end up being nil then you can pin-point the problem. JSON comes back as an arbitrary structure so chaining a bunch of calls together without any sort of testing can lead to trouble.

Resources