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,093
  • 43
  • 151
  • 267

2 Answers2

8

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
  • 113,563
  • 27
  • 250
  • 306
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
  • 113,563
  • 27
  • 250
  • 306
Max Williams
  • 31,680
  • 30
  • 120
  • 192