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.

2
  • 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. Commented Jun 25, 2014 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. Commented Jun 25, 2014 at 18:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.