1

I'm fairly new to javascript and such so I don't know if this will be worded correctly, but I'm trying to parse a JSON object that I read from a database. I send the html page the variable from a python script using Django where the variable looks like this:

{
  "data":{
    "nodes":[
      {
        "id":"n0",
        "label":"Redditor(user_name='awesomeasianguy')"
      },
      ...
    ]
  }
}

Currently, the response looks like:

"{u'data': {u'nodes': [{u'id': u'n0', u'label': u"Redditor(user_name='awesomeasianguy')"}, ...

I tried to take out the characters like u&#39 with a replaceAll type statement as seen below. This however is not that easy of a solution and it seems like there has got to be a better way to escape those characters.

var networ_json = JSON.parse("{{ networ_json }}".replace(/u'/g, '"').replace(/'/g, '"').replace(/u"/g, '"').replace(/"/g, '"'));

If there are any suggestions on a method I'm not using or even a tool to use for this, it would be greatly appreciated.

jayho
  • 13
  • 3
  • You should show how you're getting that data, how you're passing it to the template, and how you're outputting it in the template. – Daniel Roseman Jun 25 '14 at 18:25
  • The reason I reopened this question is that the problem is not with parsing characters from JSON at all, but with preventing them being created in the first place. And to fix that, as I say in the previous question, we need to know how the JSON is being output. – Daniel Roseman Jun 25 '14 at 18:47

1 Answers1

1

Use the template filter "|safe" to disable escaping, like,

var networ_json = JSON.parse("{{ networ_json|safe }}";

Read up on it here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe

rihardsp
  • 54
  • 1
  • 5
  • Thank you. This is almost exactly what I want, but after a couple of replace statements to take out the 'u' characters and such, I'm getting a syntaxerror: unexpected identifier. Any ideas? – jayho Jun 26 '14 at 14:59
  • Remember that after marking the object as safe, you can't access it's properties like {{ networ_json.foo }} anymore. Perhaps that's why youu're getting that error? Perhaps you can give me a pastebin to look at? – rihardsp Jun 26 '14 at 15:32