Search code examples
rubyjsonjira-rest-apidashing

How to parse JSON data for dashing.io


I'm currently working on a JSON parser for a dashing.io board. I am getting the information from an HTTP SSL connection to my webserver. I do not know how to combine my output properly.

This is an example of my data:

{ expand: "schema, names",
  startAt: 0,
  issues : [
    0 : {
        expand : "information"
        id: "1231425"
        fields : {
            customfield: "something"
            summary: "short summary one issue"
         },
     1 : {
        expand : "information"
        id: "1231426"
        fields : {
            customfield: "something else"
            summary: "short summary of the other issue"
         }
   ]
}

I want to create a widget which lists only the summaries of the issues. I managed to get a response which looks like:

[[{:summary=>"short summary one issue"}], [{:summary=>"short summary other issue"}]]

but I need a response which looks like:

[{:summary=>"short summary one issue"}, {:summary=>"[short summary other issue"}]

My source-code for the array is:

  (0 .. issue_count[:total] - 1).each do |i|
      @issue_summaries[i] = issue_count
         .map { |json_element| jiraParser.to_json_issue(i)}
   end

My JiraParser class, which parses the response body, looks like:

 class JiraParser
   def initialize(json_data)
     @data = json_data
   end

   def total
     @data['total']
   end

   def summary(i)
     @issues = @data['issues']
     @issue = @issues[i]
     @fields = @issue['fields']
     @fields['summary']
   end

   def to_json_total
     {:total => total}
    end

    def to_json_issue(i)
      {:summary => summary(i)}
    end
  end

I'm a newbie in Ruby so I do not have a good knowledge about the datatypes and so on.


Solution

  • You are one step from the result. As you have:

    ss = [[{:summary=>"short summary one issue"}], 
          [{:summary=>"short summary other issue"}]]
    

    just call flatten on it:

    ss.flatten
    #⇒ ss = [{:summary=>"short summary one issue"},
    #        {:summary=>"short summary other issue"}]
    

    As a matter of fact, you might get rid of redundant :summary and get an array of summaries (assuming issues contain the original Hash):

    issues[:issues].first.map { |_, v| v[:fields][:summary] }
    #⇒  [
    #  [0] "short summary one issue",
    #  [1] "short summary of the other issue"
    # ]