I’ve got an issue where I want to pass the whole data set of the profile page using data serialization as below, however the issue is that I get the output data with single quotes instead of double and I cannot parse it later on:
View:
def profile_page(request):
if request.method == 'POST':
form = WeightLogForm(request.POST)
if form.is_valid():
weight_log = form.save(commit=False)
weight_log.profile = Profile.objects.get(user=request.user)
weight_log.save()
return redirect('profile')
else:
form = WeightLogForm()
user_weight_log = WeightRecord.objects.filter(profile__user=request.user).order_by('-entry_date')
paginator = Paginator(user_weight_log, 10)
page = request.GET.get('page')
try:
user_weight_log = paginator.page(page)
except PageNotAnInteger:
user_weight_log = paginator.page(1)
except EmptyPage:
user_weight_log = paginator.page(paginator.num_pages)
serialized_data = [{'weight': str(record.weight), 'entry_date': record.entry_date.strftime('%Y-%m-%d')} for record in
user_weight_log]
return render(request, 'profile.html', {
'user_weight_log': user_weight_log,
'form': form,
'weight_data': serialized_data
})
Html Template:
<div id="weight-data" data-weight-data="{{ weight_data|safe }}"></div>
Data output:
[{‘weight’: ‘122.00’, ‘entry_date’: ‘2023-09-28’}, {‘weight’: ‘123.00’, ‘entry_date’: ‘2023-09-18’}, {‘weight’: ‘44.00’, ‘entry_date’: ‘2023-09-15’}, {‘weight’: ‘85.00’, ‘entry_date’: ‘2023-09-06’}, {‘weight’: ‘11.00’, ‘entry_date’: ‘2023-09-06’}, {‘weight’: ‘12.00’, ‘entry_date’: ‘2023-09-05’}, {‘weight’: ‘17.00’, ‘entry_date’: ‘2023-09-05’}, {‘weight’: ‘44.00’, ‘entry_date’: ‘2023-08-08’}, {‘weight’: ‘17.00’, ‘entry_date’: ‘2023-06-08’}, {‘weight’: ‘33.00’, ‘entry_date’: ‘2023-06-07’}]
Javascript:
var weightDataElement = document.getElementById('weight-data');
var weightDataJSON = weightDataElement.getAttribute('data-weight-data');
var weightData = JSON.parse(weightDataJSON);
The error I get:
Uncaught SyntaxError: JSON.parse: expected property name or ‘}’ at line 1 column 3 of the JSON data
2
Answers
JSON requires double quotes
What you’re getting is the python representation of the dictionary. As others pointed out, this is not JSON yet. To output the data as JSON.
The easiest way to do so is to use python’s
json
package and the functiondumps
which outputs the inputted data as a json string.Alternatively, for your specific case, there’s also a template filter provided by django which outputs any data as json, embedded within a
<script type="application/json">
element. You could use this in your case within the template like