0

I'm writing a simple Django + React Application in which I want to pass some JSON from Django render() to React.js. I first render an HTML page with Django, providing the JSON. Although I'm unaware of the format, the data is coming through, as I can show it using Django's template language. However, in the React code, which is called by the HTML page, I get the JSON as a string, and only the first 10 chars. I'm wondering whether there is a way to get this through properly, instead of having to write an http post every time.

My Django views script, which renders the html:

@login_required(login_url="/login/")
def index(request):
    data = {
        'key': [0, 1, 2, 3],
        'key2': 'abcd',
    }
    context = {
        'data': json.dumps(data),
        'navItem': 0,
    }
    return render(request, "index.html", context)

My index.html:

<!DOCTYPE html>
<html lang="en">
<body>
    {{data}}
    <div class="reactitem" data-json={{data}}></div>
    <script src="http://127.0.0.1:8080/index.js" charset="utf-8"></script>
</body>
</html>

And lastly my index.js (locally hosted):

document.querySelectorAll('#reactitem').forEach((domContainer) => {
    console.log(domContainer.dataset.json);
    console.log(typeof(domContainer.dataset.json));
    console.log(domContainer.dataset.json.length);
})

When I load the page, I see the full data json on screen while getting the following output in the console:

{"key":
string
7
2
  • 1
    "When I load the page, I see the full data json on screen" Seems like you need to escape the json content, and unescape when to be used. Commented Oct 15, 2020 at 11:09
  • Thanks for your comment. Escaping and unescaping seems to work, but only for strings. Do you know whether there is another way however, especially for the case of large jsons the process of (un)escaping seems very inefficient? Commented Oct 15, 2020 at 11:18

1 Answer 1

1

I have seen this concept applied in big production solutions. It is a valid approach.

Given the content has been serialized to.

<div data-json='{&quot;someKey&quot;:&quot;someValue&quot;}'></div>

Then you can de-serialize to a JS object.

const el = document.querySelector('[data-json]');
const json = JSON.parse(el.dataset.json);
console.log(json)

This renders in the console {someKey: "someValue"}

The HTML could also be this. But the ' should be escaped.

<div data-json='{"someKey":"someValue"}'></div>
Sign up to request clarification or add additional context in comments.

Comments

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.