to_json引入了奇怪的字符

时间:2018-12-07 13:58:48

标签: ruby

使用此代码,我实现了一棵树

groups = {"al1o0"=>"A1", "al2o2"=>"A10", "al2o3"=>"A11", "al1o1"=>"A2"}

map = {}
arr = []

groups.each_with_index do |group, index|
  level = (group.first.split("o")[0].split("al")[1]).to_i - 1
  level = level == 0 ? nil : level
   order = group.first.split("o")[1]
   arr.append({ :id=> index + 1, :order => order, :name => group.last, :parent => level})
end

root = {:id => 0, :name => '', :order => 0, :parent => nil}

arr.each do |e|
  map[e[:id]] = e
end

tree = {}

arr.each do |e|
  pid = e[:parent]
  if pid == nil
    (tree[root] ||= []) << e
  else
    (tree[map[pid]] ||= []) << e
  end
end

树有

 => {{:id=>0, :name=>"", :order=>0, :parent=>nil}=>[{:id=>1, :order=>"0", :name=>"A1", :parent=>nil}, {:id=>4, :order=>"1", :name=>"A2", :parent=>nil}], {:id=>1, :order=>"0", :name=>"A1", :parent=>nil}=>[{:id=>2, :order=>"2", :name=>"A10", :parent=>1}, {:id=>3, :order=>"3", :name=>"A11", :parent=>1}]} 

到目前为止,但是如果我执行tree.to_json,则输出为

 => "{\"{:id=\\u003e0, :name=\\u003e\\\"\\\", :order=\\u003e0, :parent=\\u003enil}\":[{\"id\":1,\"order\":\"0\",\"name\":\"A1\",\"parent\":null},{\"id\":4,\"order\":\"1\",\"name\":\"A2\",\"parent\":null}],\"{:id=\\u003e1, :order=\\u003e\\\"0\\\", :name=\\u003e\\\"A1\\\", :parent=\\u003enil}\":[{\"id\":2,\"order\":\"2\",\"name\":\"A10\",\"parent\":1},{\"id\":3,\"order\":\"3\",\"name\":\"A11\",\"parent\":1}]}" 

为什么在:id = \ u003e0中将:id => 0更改为?

1 个答案:

答案 0 :(得分:1)

首先,树看起来很奇怪。

{{:id=>0, :name=>"", :order=>0, :parent=>nil}=>[{:id=>1, :order=>"0", :name=>"A1", :parent=>nil}, ...]}}

这是一个关键 {:id => 0,:name =>“”,:order => 0,:parent => nil}

和 [{:id => 1,:order =>“ 0”,:name =>“ A1”,:parent => nil},...] 是一个值。

键不应为哈希。以后如何调用。

您可能需要类似

{“ A1” => {名称:'foo',顺序:'0'},'A2'=> ...}