简体   繁体   中英

Remove slash from string in ruby on rails

I need to remove "\" from below string

{\"MACAddress\":\"74:5E:78\",\"DeviceName\":\"Connected_Device\"}

Response should be

{"MACAddress":"74:5E:78","DeviceName":"Connected_Device"}

I need to check if string includes "\n",i need to add validation to remove "\"

Can you please help how to handle this in rails?

Currently i am using httpparty below code

        reqType = params['reqType']
         payLoadData = params['payLoadData']

        p "PAYLOAD DATA-------------- #{payLoadData}"
        if reqType == "post"
          start = Time.now
        url=params['url']
        body_param= device 
        p "payLoadData-------------- #{body_param}"

        response = HTTParty.post(url,
         :body => body_param,
         :headers => {'Content-Type' => 'application/json','User-Agent'=> 'Auto',"Authorization" => 'Basic=='})
        result_hash["response"].push({"body": response.body.to_s, "response_time": response_time.to_s})
        result_hash["status"].push(response.code)


JSON.parse("{\"MACAddress\":\"74:5E:78\",\"DeviceName\":\"Connected_Device\"}")

It should do the trick

The response that you get from your Ajax call is a hash in JSON format.

Just use a JSON parser to translate the JSON string into a Ruby hash:

require 'json'

pay_load = params['payLoadData']
device = JSON.parse(pay_load)

device['MACAddress']
#=> "74:5E:78"
device['DeviceName']
#=> "Connected_Device"

When you just want to output the hash a simple puts device or a <%= device %> (depending on your context) should work. Because in both cases to_s is called on the hash internally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM