Serializing a JSON object for a Django URL
<p>I have a JSON object that looks like this:</p>

<pre><code>var obj = {  
   "selection":[  
      {  
         "author":"John Doe",
         "articles":[  
            "Article One",
            "Article Two"
         ]
      }
   ]
}
</code></pre>

<p>I want to pass this object to Django to render a view that displays 'Article One' and 'Article Two' upon render. I first serialize the JSON object so that it can be appended to a URL; I use <code>$.param(obj)</code> for serialization. Now the JSON object looks something like this:</p>

<pre><code>"selection%5B0%5D%5Bauthor%5D=John+Doe&amp;selection%5B0%5D%5Barticles%5D%5B%5D=Article+One&amp;selection%5B0%5D%5Barticles%5D%5B%5D=Article+Two"
</code></pre>

<p>Now I can append this to a path and use <code>window.open(url)</code> the view will handle everything else. On the Django end, I was surprised to see that the structure of the JSON object has changed to this:</p>

<pre><code>"selection[0][author]=John+Doe&amp;selection[0][articles][]=Article+One&amp;selection[0][articles][]=Article+Two"
</code></pre>

<p>I want to be able to use the JSON object as a dict e.g.:</p>

<pre><code>obj = request.GET.get('selection')
obj = json.loads(obj)
print(obj[0].author)
...
</code></pre>

<p>How should I handle this JSON structure on the Django side of things?</p>

<p>You are not properly serializing the object to JSON, even if you say you do. The correct way would be to use <code>JSON.stringify()</code>, as @dunder states.</p>

<p>Than you parse it back to an object with <code>JSON.parse(strignifiedJson)</code>.</p>

<pre><code>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));
</code></pre>

javascript python json django