Lucien Edel Lucien Edel - 2 months ago 11
Javascript Question

Interacting with my JSON object before displaying it

Hello stack overflow community,
I'm stuck at this point for a while now and even if I went through a lot of posts to try to solve it I still don't get which way would fit the best in my case to manage to display my JSON on my HTML.

First, my JSON is a varying length string, send by my php code and receive in JS via XMLHttpRequest

var return_data = xhr.responseText;


Example of JSON format:

"output":[
{
"id":"13",
"titre":"assiette servite xxx",
"format":"dat",
"date":"2016-09-10",
"source":"DDT 68",
"description":"exemple"
},
{
"id":"16",
"titre":"releve pollution atmospherique",
"format":"shp",
"date":"2014-01-05",
"source":"agence qualite de l air",
"description":"exemple"
},


I managed to display simply my JSON string with:

document.getElementById("status").innerHTML = return_data;


But here I would rather loop it in order to style it, then send it to my HTML. I've tried a lot of different loops without success
(e.g. How do I iterate through this JSON object in jQuery?)

I need to parse my string:

var jay = JSON.parse(return_data);


But then i still don't manage to work with the different entities and display for instance in my HTML

<div id="status"></div>


id 1

titre
format
date

id 2

titre
format
date

I'm still working on it and making tests, hoping that in the meantime maybe someone could give me hints or explaining what I'm doing wrong.

example of failed test:

for(var i=0; i < jay.length; i++)
{
var add = jay[i]['titre'];
}
document.getElementById("status").innerHTML = add;


Cheers.

Answer

you should add two brackets to wrap your JSON from the server, that is not a correct JSON format, this is:

{ "output":[
       {
        "id":"13",
        "titre":"assiette servite xxx",
        "format":"dat",
        "date":"2016-09-10",
        "source":"DDT 68",
        "description":"exemple"
       },
       {
        "id":"16",
        "titre":"releve pollution atmospherique",
        "format":"shp",
        "date":"2014-01-05",
        "source":"agence qualite de l air",
        "description":"exemple"
       },
    }

And you have to add the output level in the loop:

for(var i=0; i < jay.output.length; i++)
{
  var add = jay.output[i]['titre'];
}

cheers

EDIT

    var add = [];
    for(var i=0; i < jay.output.length; i++)
        {
          add.push(jay.output[i]['titre']);
        }
   document.getElementById("status").innerHTML = add.join(', ');

This will display all elements separated by a comma.

Cheers

Comments