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!

1

1 Answer 1

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 }}';
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.