1

If I had a string :

"TimeStamp=1320947201017&enumber=34646"

And wanted this to be JSON :

{ "TimeStamp" : "1320947201017", "enumber" : "34646" }

Is there a built-in way to accomplish this in Ruby?

Trip
  • 26,756
  • 46
  • 158
  • 277

2 Answers2

9

Do as below :

require 'uri'
require 'json'

Hash[URI.decode_www_form("TimeStamp=1320947201017&enumber=34646")].to_json
# => "{\"TimeStamp\":\"1320947201017\",\"enumber\":\"34646\"}"

Documentation - decode_www_form and Generating JSON

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
5

Convert it to a hash, then convert the hash to json, both using rails' inbuilt methods.

require 'rack/utils'
#=> []
paramstring = "TimeStamp=1320947201017&enumber=34646"
#=> "TimeStamp=1320947201017&enumber=34646"
hash = Rack::Utils.parse_nested_query(paramstring)
#=> {"TimeStamp"=>"1320947201017", "enumber"=>"34646"}
hash.to_json    
#=> "{\"TimeStamp\":\"1320947201017\",\"enumber\":\"34646\"}"
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
Max Williams
  • 32,435
  • 31
  • 130
  • 197