2016-10-18 126 views
0

我有一個JSON對象,看起來像這樣:序列化JSON對象的Django的URL

var obj = { 
    "selection":[ 
     { 
     "author":"John Doe", 
     "articles":[ 
      "Article One", 
      "Article Two" 
     ] 
     } 
    ] 
} 

我想通過這個對象來Django的渲染,顯示「壹條」的景色,「第二條'渲染後。我首先序列化JSON對象,以便它可以附加到URL;我使用$.param(obj)進行序列化。現在,JSON對象看起來是這樣的:

"selection%5B0%5D%5Bauthor%5D=John+Doe&selection%5B0%5D%5Barticles%5D%5B%5D=Article+One&selection%5B0%5D%5Barticles%5D%5B%5D=Article+Two" 

現在我可以把這段路徑和使用window.open(url)視圖會處理一切。在Django的結束,我很驚訝地看到,JSON對象的結構發生了變化,以這樣的:

"selection[0][author]=John+Doe&selection[0][articles][]=Article+One&selection[0][articles][]=Article+Two" 

我希望能夠使用JSON對象作爲字典如:

obj = request.GET.get('selection') 
obj = json.loads(obj) 
print(obj[0].author) 
... 

我應該如何在Django方面處理這個JSON結構?

+0

我可能不在這裏。但是,你不能使用'JSON.stringify',然後編碼併發送到視圖? – dunder

+0

@dunder你很重要。我完全錯過了'encodeURIComponent()',因爲我認爲'$。param()'是唯一的出路。 – FatHippo

+0

很酷。爲什麼你要在'GET'調用中使用'json'?同樣,使用'author'和'articles'參數可以實現同樣的效果嗎? – dunder

回答

0

即使你說你這樣做,你也沒有正確地將對象序列化爲JSON。正確的方法是使用JSON.stringify()作爲@dunder狀態。

比你解析它回到一個對象JSON.parse(strignifiedJson)

var obj = { 
    "selection":[ 
     { 
     "author":"John Doe", 
     "articles":[ 
      "Article One", 
      "Article Two" 
     ] 
     } 
    ] 
} 
// Stringify and encode 
var objAsParam = encodeURIComponent(JSON.stringify(obj)); 

// Send as a param, for example like http://example.com?obj=YourStringifiedObject... 

// Parse it back: 
var parsedObj = JSON.parse(decodeURIComponent(objAsParam)); 
+0

'encodeURIComponent(JSON.stringify(obj))'爲我做了訣竅。我也意識到我應該將該參數添加到URL中,即''... /?selection ='+ '。 – FatHippo