Search code examples
javascriptjsonajaxapidjango-models

How to loop through JSON from JSON.parse?


I requested some data from my django server. Then I used JSON.parse to deserialized the data into a JSON object.I want to loop through each object field attribute and call the function createDiv on each of them.

  function load_blog(){

  let start_blog = 0
  let end_blog = 4

  fetch(`/blog/?start=${start_blog}&end_blog=${end_blog}`)
  .then(response => response.json())
  .then(json_blogs => {
    var jsblog = JSON.parse(json_blogs)
    jsblog.fields.forEach()

  })
}

This is how my data looks after using JSON.parse enter image description here

I would like to use the function on each field dict.However I'm getting this error:

jsblog.fields is undefined

And I'm clearly seeing fields from the console. So could anyone assist me?


Solution

  • First things first, if I'm right, jsblog is an array of Objects, right?

    Thus if you want to iterate on jsblog, you might want to do that in this way: jsblog.forEach(...). Then in the callback, you can reference fields property of each object.

    jsblog.forEach(blogObject => console.log(blogObject.fields));
    

    By jsblog.fields, you tried to access the property called fields of the array of objects, which shall be undefined. jsblog does not have fields property, but the children of jsblog do.