解析JSON输出时输出中的空间

时间:2018-10-07 20:14:15

标签: ruby-on-rails ruby ruby-on-rails-4

我从以下curl命令的JSON输出中解析了值(由于stackoverflow),

1。),但我在输出中看到很大的空间(附加了示例图像以供参考)。需要输出而没有多余的空格(请在输出的末尾看到多余的空格,请参阅图片。)对此有帮助,

(对于红宝石的道歉,这是基本的东西)

space after last line of output

2。)每个值后面也需要空格。

样品输出:

ID : 7j6rzn1r43zz , CREATED AT : 2017-04-03T12:08:03Z , LINK : http://stspg.io/5Es5 , ISSUE NAME : Intermittent Issue , DESCRIPTION :  There  is a minor performance degradation in our app for some customers in US, We are working on it , STATUS : identified ,DESCRIPTION :  We have resolved the performance issue in our app, We are closely monitoring it. , STATUS : resolved
ID : g8tk0jtvgybt , CREATED AT : 2017-04-01T11:11:27Z , LINK : http://stspg.io/5EHd , ISSUE NAME : Intermittent Issue , DESCRIPTION :  Currently we are facing delay in incoming emails as we have problem with our email service provider. We are working on it. , STATUS : investigating ,DESCRIPTION :  The delay in incoming emails issue has been resolved now. Application is working fine. , STATUS : resolved

预期

ID : 7j6rzn1r43zz , CREATED AT : 2017-04-03T12:08:03Z , LINK : http://stspg.io/5Es5 , ISSUE NAME : Intermittent Issue , DESCRIPTION :  There  is a minor performance degradation in our app for some customers in US, We are working on it , STATUS : identified ,DESCRIPTION :  We have resolved the performance issue in our app, We are closely monitoring it. , STATUS : resolved

ID : g8tk0jtvgybt , CREATED AT : 2017-04-01T11:11:27Z , LINK : http://stspg.io/5EHd , ISSUE NAME : Intermittent Issue , DESCRIPTION :  Currently we are facing delay in incoming emails as we have problem with our email service provider. We are working on it. , STATUS : investigating ,DESCRIPTION :  The delay in incoming emails issue has been resolved now. Application is working fine. , STATUS : resolved

卷曲:

def incidents

value = `curl https://api.statuspage.io/v1/pages/incidents.json -H "Authorization: OAuth a8ef"`

data_hash = JSON.parse(value).map {|h| puts "ID : #{h["id"]} , CREATED AT : #{h["created_at"]} , LINK : #{h["shortlink"]} , ISSUE NAME : #{h["name"]} , DESCRIPTION :  #{h["incident_updates"][1]["body"]} , STATUS : #{h["incident_updates"][1]["status"]} ,DESCRIPTION :  #{h["incident_updates"][0]["body"]} , STATUS : #{h["incident_updates"][0]["status"]}"}

puts data_hash


end

1 个答案:

答案 0 :(得分:3)

您可以在map迭代器中执行输出,然后再执行其他puts。不必要,如您所见,会导致不必要的输出。

map替换为each,然后删除最后一个puts。像这样:

  JSON.parse(value).each do |h|
    puts "ID : #{h["id"]} , CREATED AT : #{h["created_at"]} , LINK : #{h["shortlink"]} , ISSUE NAME : #{h["name"]} , DESCRIPTION :  #{h["incident_updates"][1]["body"]} , STATUS : #{h["incident_updates"][1]["status"]} ,DESCRIPTION :  #{h["incident_updates"][0]["body"]} , STATUS : #{h["incident_updates"][0]["status"]}"
  end