0

I am implementing some jquery code for filtering, which initially takes data from a json file:

function getProducts() {
$.get("products.json", (products) => {
  ...;
})

However, instead of fetching a json file, I'd like to use a json-like array and use that instead of the json file. This data would come from the Django backend, which would pass the data onto the html template.

Something like this:

var products = {{jsonData}}

which would then be this:

var products = [
  {
    "id": 1,
    "category": "shirts",
    "name": "Fantasy T-shirt",
    "rating": 4,

  },
  {
    "id": 2,
    "category": "hoodies",
    "name": "Wolf Hoodie",
    "rating": 5,
  },
]

How could I modify the jquery code to accept that?

Thanks!

5
  • Where is that json-like array coming from ? not clear what are trying to do ? Commented Sep 14, 2020 at 8:03
  • 1
    Do you mean you want to convert products (which is a string in your function) to an array? Then use products = JSON.parse(products) inside that function. It will work if the json string is valid. See JSON.parse() Commented Sep 14, 2020 at 8:05
  • @AlwaysHelping I've edited the question. The data would be provided by the Django backend, which would be passed in the correct format. Does that make sense? Commented Sep 14, 2020 at 8:07
  • 1
    Why not use a $.each function in your $.get and get all the data from your array and then populate it where the data needs to appear. Commented Sep 14, 2020 at 8:09
  • @verjas What would be the syntax? Something like below? $.get(JSON.parse(products), (products) => { Commented Sep 14, 2020 at 9:30

1 Answer 1

1

You can pass Json array from view to template by returning it

from django.http import JsonResponse

return JsonResponse({'key1':var1})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Follow-up question: Where would the json array go inside this code: javascript function getProducts() { $.get("products.json", (products) => { ...; })
I don't know, sorry :( My javascript skill is less than basic.

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.