skip to Main Content

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


  1. var weightDataElement = document.getElementById('weight-data');
    console.log(weightDataElement);
    var weightDataJSON = weightDataElement.getAttribute('data-weight-data');
    console.log(weightDataJSON);
    var weightData = JSON.parse(weightDataJSON);
    console.log(weightData);
    <div id="weight-data" data-weight-data="[{&quot;weight&quot;: &quot;122.00&quot;, &quot;entry_date&quot;: &quot;2023-09-28&quot;}, {&quot;weight&quot;: &quot;123.00&quot;, &quot;entry_date&quot;: &quot;2023-09-18&quot;}, {&quot;weight&quot;: &quot;44.00&quot;, &quot;entry_date&quot;: &quot;2023-09-15&quot;}, {&quot;weight&quot;: &quot;85.00&quot;, &quot;entry_date&quot;: &quot;2023-09-06&quot;}, {&quot;weight&quot;: &quot;11.00&quot;, &quot;entry_date&quot;: &quot;2023-09-06&quot;}, {&quot;weight&quot;: &quot;12.00&quot;, &quot;entry_date&quot;: &quot;2023-09-05&quot;}, {&quot;weight&quot;: &quot;17.00&quot;, &quot;entry_date&quot;: &quot;2023-09-05&quot;}, {&quot;weight&quot;: &quot;44.00&quot;, &quot;entry_date&quot;: &quot;2023-08-08&quot;}, {&quot;weight&quot;: &quot;17.00&quot;, &quot;entry_date&quot;: &quot;2023-06-08&quot;}, {&quot;weight&quot;: &quot;33.00&quot;, &quot;entry_date&quot;: &quot;2023-06-07&quot;}]"></div>

    JSON requires double quotes

    Login or Signup to reply.
  2. 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 function dumps which outputs the inputted data as a json string.

    from json import dumps
    
    # ...
    
    # use dumps to serialize the data to json format
    serialized_data = dumps([{'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
    })
    

    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

    {{ weight_data|json_script:"weight-data" }}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search