如何在Ruby中解析字符串的字符串?

时间:2021-10-31 16:01:11

I am working with an API that is returning a "JSON string"...which means that it's returning text wrapped with double quotes:

我正在使用返回“JSON字符串”的API ...这意味着它返回包含双引号的文本:

response = HTTParty.get('http://api.example.com')
response.body == '"token"'

For all of my requests, I am abstracting the API request and automatically using JSON.parse(response.body), but in this case, it chokes on the string because it's not a JSON object.

对于我的所有请求,我正在抽象API请求并自动使用JSON.parse(response.body),但在这种情况下,它会阻塞字符串,因为它不是JSON对象。

I guess I can add an extra logic branch to check if it's a string, don't parse as JSON. How should I extract the string out of this string?

我想我可以添加一个额外的逻辑分支来检查它是否是一个字符串,不要解析为JSON。我应该如何从这个字符串中提取字符串?

3 个解决方案

#1


1  

Use regex

使用正则表达式

s = '"token"'
str = s[/\A"(.+)"\Z/, 1]
puts str # => token

#2


1  

Try:

尝试:

JSON.parse(response.body) rescue response.body[1..-2]

#3


1  

Why not sniff for the normal JSON open/close characters [...] and {...} used to define objects?

为什么不嗅探用于定义对象的普通JSON打开/关闭字符[...]和{...}?

Here's how objects look converted to JSON:

以下是对象看起来如何转换为JSON:

require 'json'

puts JSON[{'foo' => 1}]
puts JSON[[1, 2]]
# >> {"foo":1}
# >> [1,2]

Checking to make sure those are valid string representations:

检查以确保它们是有效的字符串表示形式:

JSON['{"foo":1}'] # => {"foo"=>1}
JSON['[1,2]'] # => [1, 2]

Here's how I'd write some code to sniff whether the string passed in looks like a valid JSON string, or just a string with wrapping double-quotes:

下面是我如何编写一些代码来嗅探传入的字符串是否看起来像一个有效的JSON字符串,或者只是一个包含双引号的字符串:

require 'json'

def get_object(str)
  if str[/^[{\[].+[}\]]$/]
    JSON[str]
  else
    str[1..-2]
  end
end

get_object('{"foo":1}') # => {"foo"=>1}
get_object('{"foo":1}').class # => Hash
get_object('[1,2]') # => [1, 2]
get_object('[1,2]').class # => Array
get_object("'bar'") # => "bar"

Notice that on the last line the string 'bar' that's enclosed in single-quotes, is returned as a bare string, i.e., there is no wrapping set of single-quotes so the string is no longer quoted.

请注意,在最后一行中,用单引号括起来的字符串'bar'作为一个裸字符串返回,即没有单引号的包装集,因此不再引用该字符串。

It's possible you'd receive a string with white-space leading or following the payload. If so, do something like:

您可能会收到一个带有空白字符串或跟随有效负载的字符串。如果是这样,请执行以下操作:

def get_object(str)
  if str.strip[/^[{\[].+[}\]]$/]
    JSON[str]
  else
    str.strip[1..-2]
  end
end

get_object('  {"foo":1}') # => {"foo"=>1}
get_object('  [1,2]  ') # => [1, 2]
get_object(" 'bar'") # => "bar"

#1


1  

Use regex

使用正则表达式

s = '"token"'
str = s[/\A"(.+)"\Z/, 1]
puts str # => token

#2


1  

Try:

尝试:

JSON.parse(response.body) rescue response.body[1..-2]

#3


1  

Why not sniff for the normal JSON open/close characters [...] and {...} used to define objects?

为什么不嗅探用于定义对象的普通JSON打开/关闭字符[...]和{...}?

Here's how objects look converted to JSON:

以下是对象看起来如何转换为JSON:

require 'json'

puts JSON[{'foo' => 1}]
puts JSON[[1, 2]]
# >> {"foo":1}
# >> [1,2]

Checking to make sure those are valid string representations:

检查以确保它们是有效的字符串表示形式:

JSON['{"foo":1}'] # => {"foo"=>1}
JSON['[1,2]'] # => [1, 2]

Here's how I'd write some code to sniff whether the string passed in looks like a valid JSON string, or just a string with wrapping double-quotes:

下面是我如何编写一些代码来嗅探传入的字符串是否看起来像一个有效的JSON字符串,或者只是一个包含双引号的字符串:

require 'json'

def get_object(str)
  if str[/^[{\[].+[}\]]$/]
    JSON[str]
  else
    str[1..-2]
  end
end

get_object('{"foo":1}') # => {"foo"=>1}
get_object('{"foo":1}').class # => Hash
get_object('[1,2]') # => [1, 2]
get_object('[1,2]').class # => Array
get_object("'bar'") # => "bar"

Notice that on the last line the string 'bar' that's enclosed in single-quotes, is returned as a bare string, i.e., there is no wrapping set of single-quotes so the string is no longer quoted.

请注意,在最后一行中,用单引号括起来的字符串'bar'作为一个裸字符串返回,即没有单引号的包装集,因此不再引用该字符串。

It's possible you'd receive a string with white-space leading or following the payload. If so, do something like:

您可能会收到一个带有空白字符串或跟随有效负载的字符串。如果是这样,请执行以下操作:

def get_object(str)
  if str.strip[/^[{\[].+[}\]]$/]
    JSON[str]
  else
    str.strip[1..-2]
  end
end

get_object('  {"foo":1}') # => {"foo"=>1}
get_object('  [1,2]  ') # => [1, 2]
get_object(" 'bar'") # => "bar"