1

I am attempting to read a Django object in javascript. I have serialized the django model object like so:

recent_data = leafSamples.objects.filter(field_name=str(fields_distinct[0])).latest('id')
recent_data_json = serializers.serialize('json', [recent_data])

Next I have tried to parse the JSON data in javascript:

var recentData = {{recent_data_json |safe}};
parsedData = JSON.parse(recentData);
console.log(parsedData)

However, I keep receiving an error:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

When stringified, my data looks like this:

[
    {
        "fields": {
            "copper": "21",
            "guess": null,
            "zinc": "32",
            "chloride": "",
            "potassium": "2.36",
            "irrigation": null,
            "manganese": "19",
            "calcium": "1.81",
            "iron": "66",
            "magnesium": "0.37",
            "nitrogen": "3.14",
            "boron": "46",
            "date": "2018-04-08",
            "sulfur": "0.33",
            "field_name": "104A",
            "age": null,
            "phosphorus": "0.40"
        },
        "model": "scoutapp.leafsamples",
        "pk": 1126
    }
]

How can I parse my data in the "fields" property? I would like to be able to have parsedData.copper return "21," or something to that effect. Thanks!

crushendo
  • 33
  • 2
  • 9
  • possible duplicate of https://stackoverflow.com/questions/7165656/passing-objects-from-django-to-javascript-dom – Ganesh Negi Apr 19 '18 at 19:52

1 Answers1

0

JSON.parse parses strings, but you are feeding it with a list. You may try adding single quotes and escapejs filter:

var recentData = '{{recent_data_json | safe | escapejs }}';
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • 1
    Yes, this gave me the desired result. And then, to access a specific value within the "fields" object, I had to use for example: console.log(parsedData[0].fields.copper), which returned "21" as desired. – crushendo Apr 20 '18 at 12:32