如何将字符串转换为哈希

时间:2012-09-10 11:59:30

标签: ruby string hash

这是我的字符串

"{web:{url:http://www.example.com,toke:somevalue},username:person}"

我想将其转换为哈希,如下所示:

```

{
  'web' =>  {
     'url'  => "http://www.example.com",
     'token' => 'somevalue'
   },
   'username' =>  "person"
}

```

3 个答案:

答案 0 :(得分:1)

您必须编写自定义解析器。它几乎是json,但由于值没有引用,它不会用JSON解析器解析,所以除非你能得到引用值,否则你必须手工解析它。

处理值中的冒号,逗号和花括号将是一项挑战。

答案 1 :(得分:1)

简单的解析器,仅在几个示例上进行了测试。

用法:

parse_string("{web:{url:http://www.example.com,toke:somevalue},username:person}")
=> {"web"=>{"url"=>"http://www.example.com", "toke"=>"somevalue"}, "username"=>"person"} 

解析器代码:

class ParserIterator
  attr_accessor :i, :string
  def initialize string,i=0
    @i=i
    @string=string
  end

  def read_until(*sym)
    res=''
    until sym.include?(s=self.curr)
      throw 'syntax error' if s.nil?
      res+=self.next
    end
    res
  end

  def next
    self.i+=1
    self.string[self.i-1]
  end

  def get_next
    self.string[self.i+1]
  end

  def curr
    self.string[self.i]
  end

  def check(*sym)
    throw 'syntax error' until sym.include?(self.next)
  end

  def check_curr(*sym)
    throw 'syntax error' until sym.include?(self.curr)
  end
end

def parse_string(str)
  parse_hash(ParserIterator.new(str))
end


def parse_hash(it)
  it.check('{')
  res={}
  until it.curr=='}'
    it.next if it.curr==','
    k,v=parse_pair(it)
    res[k]=v
  end
  it.check('}')
  res
end

def parse_pair(it)
   key=it.read_until(':')
   it.check(':')
   value=(it.curr=='{' ? parse_hash(it) : it.read_until(',','}'))
   return key,value   
end

答案 2 :(得分:1)

我建议使用ActiveSupport :: JSON.decode,假设您有宝石可用或愿意将其包含在您的宝石列表中。

一个问题是要有一串json。所以如果你有哈希,你可以调用#to_json来获取json字符串。例如,这有效:

str = '{"web":{"url":"http://www.example.com","toke":"somevalue"},"username":"person"}'
ActiveSupport::JSON.decode(str)
相关问题