2011-11-18 31 views
0

所以我試圖從我的數據庫中提取節點(通過遞歸),然後顯示json代碼,我必須一個JavaScript庫。問題是庫不能識別json數組輸出,因爲它有多餘的引號和斜槓(/)。下面是代碼:使用紅寶石生成節點,並顯示它們與JavaScript錯誤

data = { 
"nodes": 
"\"User1:{'color':'green','shape':'dot','label':'You'}, 
User2:{'color':'green','shape':'dot','label':'You'}, 
User3:{'color':'green','shape':'dot','label':'You'}\"" 
,"edges":{}}; 

而且我希望它看起來是這樣的:

var data = { 
        "nodes":{ 
        "You":{'color':'green','shape':'dot','label':'You'}, 
        Ben:{'color':'black','shape':'dot','label':'Ben'}, 
        David:{'color':'black','shape':'dot','label':'David'} 
        }, 
        "edges":{ 
        You:{ Ben:{}, David:{} }, 
        Ben:{ David:{}} 
        } 
       }; 

在我user_controller我使用這個:

def make_json(node, string = "") 
     node[1].each do |n| 
     string += node[0] + "{'color':'green','shape':'dot','label':'You'}," 
     return make_json(n, string) 
     end 
     return string + node[0] + "{'color':'green','shape':'dot','label':'You'}" 

    end 

最後,這樣的:

@data = {} 
    @data['nodes'] = make_json(@user_tree[0]).to_json 
    @data['edges'] = {} 

我試過使用替換方法,但數據變量似乎不是一個字符串,所以我不能只替換引號。我會很感激任何幫助。

謝謝!

回答

0

輸出中額外的\"的原因在於,您要對make_json方法的返回值調用to_json這是一個字符串。

它很難看到什麼你想在make_json做的,但假設你要使用的輸出值在@data哈希,然後將其轉換成JSON我想你會過得更好爲make_json構建散列並返回。通常,在返回JSON響應時,最簡單的解決方案是從Ruby哈希和數組構建數據結構,然後在此處調用to_json。這裏是一個大大簡化的例子(我不知道@user_tree是什麼,所以我不明白遞歸一步,但我希望這給你的總體思路):

def make_json(node, hash = {}) 
    node[1].each do |n| 
    hash[n[0]] = {:color => 'green', :shape => 'dot', :label => n[0]} 
    end 
    hash 
end 

如果試圖構建JSON串起你自己很容易絆倒。您所說的目標輸出不是有效的JSON,儘管它可能是有效的JavaScript。字符串需要用雙引號括起來,例如

"Ben": {"color": "black", "shape": "dot", "label": "Ben"} 

而不是:

Ben:{'color':'black','shape':'dot','label':'Ben'} 
+0

非常感謝!這很有幫助。 –