Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: `no implicit conversion of String into Integer` for getting json field

I got a json file like this responsed from xml-rpc server:

{
  "total_asr": -1,
  "report": [
{
  "logout_time_formatted": "2013-12-07 15:19",
  "caller_id": "",
  "user_id": x,
  "bytes_in": "964826",
  "login_time_formatted": "2013-12-07 13:46",
  "details": [
    [
      "terminate_cause",
      "Lost-Carrier"
    ],
    [
      "service",
      "x"
    ],
    [
      "nas_port_type",
      "Ethernet"
    ],
    [
      "mac",
      "x:x:x:C6:63:DE"
    ],
    [
      "assigned_ip",
      "x.x.65.139"
    ],
    [
      "port",
      "x"
    ]
  ],
  "ras_description": "x",
  "service_type": "Internet",
  "username": "x",
  "successful": "t",
  "bytes_out": "423928",
  "before_credit": 10029.29841,
  "connection_log_id": 49038,
  "billed_duration": 5562,
  "credit_used": 11.25756,
  "retry_count": 1,
  "parent_isp_credit_used": 0.0,
  "duration_seconds": 5563.0,
  "remote_ip": "5.200.65.139"
},
.
.
.
],
  "total_rows": "85",
  "total_voip_provider_credit_used": -1,
  "total_credit": -1,
  "total_duration": -1,
  "total_out_bytes": -1.0,
  "total_billed_duration": -1,
  "total_in_bytes": -1.0,
  "total_acd": -1
}

I want to get some field of that: result = {}

    rpc = IbsXmlRpc.new
    res = rpc.getConnectionLogs("200")

    result = res["report"].map{|key| 
        {
            "duration" => (key["duration_seconds"].to_i/60).to_s,
            "bytes_in" => (key["bytes_in"].to_i/1024).to_s,
            "bytes_out" => (key["bytes_out"].to_i/1024).to_s,
        }
    }

Everything works fine so far, but when i am going to get last fields of json:

    result["total_duration"] = res["total_duration"].to_s
    result["total_out_bytes"] = res["total_out_bytes"].to_s
    result["total_in_bytes"] = res["total_in_bytes"].to_s

i get this error: no implicit conversion of String into Integer I really do not know what is going on and tested everything i knew about. Any idea why this happens?

like image 232
Kaveh Avatar asked Dec 08 '13 06:12

Kaveh


1 Answers

result is not a Hash; it's an Array of Hashes. You can't access an Array index by a String. If you want to store your totals in the same structure as your "report"s, you will need to put them all in a new Hash.

rpc = IbsXmlRpc.new
res = rpc.getConnectionLogs("200")

reports = res["report"].map{|key| 
    {
        "duration" => (key["duration_seconds"].to_i/60).to_s,
        "bytes_in" => (key["bytes_in"].to_i/1024).to_s,
        "bytes_out" => (key["bytes_out"].to_i/1024).to_s,
    }
}

result = {
    :reports => reports,
    :total_duration => res["total_duration"],
    :total_out_bytes => res["total_out_bytes"],
    :total_in_bytes => res["total_in_bytes"],
}
like image 53
Jason Barnabe Avatar answered Oct 27 '22 00:10

Jason Barnabe