fbssn fbssn - 4 years ago 204
Ruby Question

Ruby and Json Data parsing for dashing.io

I'm currently working on a Json parser for a dashing.io board. I've an http ssl connection to my webserver I'm getting the information from. My problem is that I do not know how to combine my output properly.

Example of 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"
}
]
}


Now my question is: I want to create a widget which lists only the summary's 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 sourcecode 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 knowing about the datatypes and so on. As well I hope that I've provided enough information to solve the problem...

Thank you!

Answer Source

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"
# ]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download