0

I have a JSON data and a div in the code. I want to get the connections data from the JSON file to the people-update-container div. I tried the below code. But that is not working. Please help me to get the data from connections from the JSON file. JSOn data and the people-update-container files are in a same HTML page. Thank you.

var feed_json = [{  
     
     'teams' : [    {"total_count": '32'},
        "count" : "10",
                      "url"       : ""
                    },
                    { "id" : "id2", 
                      "name" : "Group 2",
                      "count" : "55",
                      "url"       : ""
        }        
     
     ],
     
     'connections': [  {'total_count' : '110'},
                    
                    { "id" : "id1",
                       "name" : "Gossip Gang",
                       "count" : "20",
                       "url"       : ""
                    },
                    { "id" : "id2", 
                       "name" : "JEC Folks",
                       "count" : "90",
                       "url"       : ""
                    }                    
                 ]
                
}];



var feedConnections = feed_json.connections;

  for(var i = 0; i < feedConnections.length; i++ ) {
   var connection = feedConnections[i];

   var id = connection.id;
   var name = connection.name;
   var count = connection.count;

   var connectionFeed = $('<div><div  id = '+ id +'  style = "margin-top: 10px;"> <span class="expandIcon1" style="float: right;"> <img  width="28" height="28" src="/media/images/icons/arrow-Down-lines.png"/> </span> <span class="barTitle">'+ name + '<span>  (' + count + ')</span></span></div></div>');

   $('.people-update-container').append(connectionFeed);
  }
<div class = "people-update-container" style = "display: none;">

</div>
Melbin Mathai
  • 487
  • 8
  • 26
  • remove "[ ]" around your json string – maxeh Aug 17 '16 at 06:45
  • 1
    Don't know if I am the only one that noticed but you have invalid JSON data in your teams property. – Erick Boshoff Aug 17 '16 at 06:46
  • Your JSON is invalid. – Marin Takanov Aug 17 '16 at 06:47
  • @MarinTakanov I don't know, how to fix the JSON. Will you please help me. – Melbin Mathai Aug 17 '16 at 06:58
  • @MelbinMathai First create an object `var foo = {bar:1}` and then use `JSON.stringify` - `var baz = JSON.stringify(foo);`. Now `baz` represent a JSON. If you want to use the JSON, parse it back to JavaScript object as folloing - `var parsedJson = JSON.parse(baz);`. Before using `stringify` and `parse`, make sure your object is a valid JavaScript object, because the one you post is invalid. I recommend you to use WebStorm as JavaScript IDE, it will make your life better. – Marin Takanov Aug 17 '16 at 07:12

5 Answers5

1
var connections = connections[0] /* !!! */
for (var key in connections) { // You're not iterating an array, but the object inside!

            var id = connections[key].id;
            var name = connections[key].name;
            var count = connections[key].count;

}
1

ost browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:

var json = '{"result":true,"count":1}',
    obj = JSON.parse(json);

alert(obj.count);

For the browsers that don't you can implement it using json2.js.

As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:

var json = '{"result":true,"count":1}',
    obj = JSON && JSON.parse(json) || $.parseJSON(json);

This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.

This Code is Imported from this link

Community
  • 1
  • 1
1

Your Json is invalid. Try to validate json using jsonlint.com Here is the valid one.

{
"teams": [{
        "total_count": "32",
        "count": "10",
        "url": ""
    }, {
        "id": "id2",
        "name": "Group 2",
        "count": "55",
        "url": ""
    }

],

"connections": [{
        "total_count": "110"
    },

    {
        "id": "id1",
        "name": "Gossip Gang",
        "count": "20",
        "url": ""
    }, {
        "id": "id2",
        "name": "JEC Folks",
        "count": "90",
        "url": ""
    }
]

}
Nikhil Dinesh
  • 3,359
  • 2
  • 38
  • 41
1

This will work. Resolve jquery error by adding jquery cdn path The problem was with your json data, which has some error.

var feed_json = {
"teams": [{
  "total_count": "32",
  "count": "10",
  "url": ""
 }, {
  "id": "id2",
  "name": "Group 2",
  "count": "55",
  "url": ""
 }

],

"connections": [{
  "total_count": "110"
 },

 {
  "id": "id1",
  "name": "Gossip Gang",
  "count": "20",
  "url": ""
 }, {
  "id": "id2",
  "name": "JEC Folks",
  "count": "90",
  "url": ""
 }
]

};


var feedConnections = feed_json.connections;

  for(var i = 0; i < feedConnections.length; i++ ) {
   var connection = feedConnections[i];

   var id = connection.id;
   var name = connection.name;
   var count = connection.count;

   //var connectionFeed = $('<div><div  id = '+ id +'  style = "margin-top: 10px;"> <span class="expandIcon1" style="float: right;"> <img  width="28" height="28" src="/media/images/icons/arrow-Down-lines.png"/> </span> <span class="barTitle">'+ name + '<span>  (' + count + ')</span></span></div></div>');

  // $('.people-update-container').append(connectionFeed);
alert(name);
  }
<div class = "people-update-container" style = "display: none;">

</div>
Nikhil Dinesh
  • 3,359
  • 2
  • 38
  • 41
  • I have one doubt, when it try to run, in the alert it showing an "undefined" thing. In my project also it showing as a separate div? Will u please Explain Why? – Melbin Mathai Aug 17 '16 at 08:26
  • { "total_count": "32", "count": "10", "url": "" } This is the first element in your json array. It doesnot have "name" parameter. All the other elements has name parameter. Thats the reason why its as undefiend. – Nikhil Dinesh Aug 17 '16 at 08:42
1

You can get JSON data via XHR request:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var json_data = JSON.parse(xhttp.responseText);
        var connections = json_data.connections;

        /* Do something with the data */
    }
};
xhttp.open("GET", "/path/to/json/file.json", true);
xhttp.send();

But before you have to format data as correct JSON, like this:

{
    teams: [ ... ],
    connections: [ ... ]
}

Read about JSON here.

jedrzejginter
  • 402
  • 3
  • 10