You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails中移除字符串反斜杠及相关处理求助

How to Remove Backslashes and Handle Escaped Newlines in Rails with HTTParty

Let's break down how to implement your requirements step by step, with robust, Rails-friendly code:

1. Safely Remove JSON Escape Backslashes

Your first goal is to convert escaped JSON strings (like "{\"MACAddress\":\"74:5E:78\"}") into valid, unescaped JSON. The safest way to do this in Ruby is using the built-in JSON library—this avoids breaking valid JSON structure that manual string replacements might mess up.

If your payLoadData is an escaped JSON string, parse it into a Ruby hash. This automatically strips unnecessary escape backslashes. When you pass this hash to HTTParty's body parameter, it will convert it back to properly formatted JSON for the request.

2. Handle Escaped Newlines (\\n)

To remove the backslash from escaped newlines (turning \\n into a real newline character \n), we'll create a helper method that recursively processes nested values (since your payload might be a nested hash or array).

3. Updated Full Code

Here's how to integrate all this into your existing Rails code, with error handling for robustness:

require 'json'
require 'httparty'

def your_controller_action_name
  result_hash = { "response" => [], "status" => [] }
  req_type = params['reqType']
  payload_data = params['payLoadData']
  
  Rails.logger.info "Original PAYLOAD DATA: #{payload_data}"

  if req_type == "post"
    start_time = Time.now
    url = params['url']
    
    begin
      # Step 1: Parse escaped JSON into a Ruby hash (removes quote escape backslashes)
      parsed_payload = JSON.parse(payload_data)
      
      # Step 2: Replace escaped newlines (\n) with actual newlines
      parsed_payload = deep_replace_escaped_newlines(parsed_payload)
      
      Rails.logger.info "Processed PAYLOAD: #{parsed_payload}"

      # Send HTTP request with processed payload
      response = HTTParty.post(url, 
        body: parsed_payload, 
        headers: {
          'Content-Type' => 'application/json',
          'User-Agent' => 'Auto',
          'Authorization' => 'Basic=='
        }
      )

      # Calculate response time and update result hash
      response_time = (Time.now - start_time).round(2)
      result_hash["response"].push({ 
        body: response.body.to_s, 
        response_time: response_time.to_s 
      })
      result_hash["status"].push(response.code)
    rescue JSON::ParserError => e
      Rails.logger.error "Failed to parse payload: #{e.message}"
      # Handle invalid JSON error
      result_hash["response"].push({ body: "Invalid JSON payload: #{e.message}", response_time: "0" })
      result_hash["status"].push(400)
    rescue HTTParty::Error => e
      Rails.logger.error "HTTP request failed: #{e.message}"
      # Handle HTTP request failures
      result_hash["response"].push({ body: "Request failed: #{e.message}", response_time: "0" })
      result_hash["status"].push(500)
    end
  end

  # Return or render the result_hash as needed for your use case
  render json: result_hash
end

# Helper method to recursively replace escaped newlines in nested data
def deep_replace_escaped_newlines(obj)
  case obj
  when Hash
    obj.transform_values { |value| deep_replace_escaped_newlines(value) }
  when Array
    obj.map { |item| deep_replace_escaped_newlines(item) }
  when String
    obj.gsub('\\n', "\n")
  else
    obj # Leave non-string values unchanged
  end
end

Key Notes:

  • Why JSON.parse is better: It only removes backslashes that are valid JSON escape characters (like those around quotes), so you won't accidentally break other parts of your payload.
  • Error handling: Added rescue blocks for invalid JSON and HTTP request failures to make your code resilient to edge cases.
  • Logging: Swapped p for Rails.logger to follow Rails best practices for production-ready logging.

内容的提问来源于stack exchange,提问作者Subashini Raja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:57:59