Rehaan Kkhaan
Rehaan Kkhaan

Reputation: 81

how to display complete array?

I am getting this error: [object Object],[object Object],[object Object].

I want to display complete array like this: John Doe, Anna Smith, Peter Jones

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees;
</script>

</body>
</html>

Upvotes: 2

Views: 122

Answers (3)

Shakir Ahamed
Shakir Ahamed

Reputation: 1308

If you want to print the all names you can do like this, If you want to load JSON from external file you have to keep JSON file on some where else on your system and you can load it using $.getJSON like below

var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';  //// keep this in an external file

$.getJSON('/path', function(data) {

   obj = JSON.parse(data);
    for (var i = 0; i < obj.employees.length; i++)
    {
       document.getElementById("demo").innerHTML += obj.employees[i].firstName + " " + obj.employees[i].lastName + ",";
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

Upvotes: 0

Jaromanda X
Jaromanda X

Reputation: 1

your array is an array of objects - you'll need to do some more coding to get it how you want it - consider using Array#map, then a Array#join to format the output as you want

var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.employees.map(function(emp) {
    return emp.firstName + ' ' + emp.lastName;
}).join(', ');

for ES2015 completeness

document.getElementById("demo").innerHTML = obj.employees.map(emp => emp.firstName + ' ' + emp.lastName).join(', ');

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You coud use Array#map and build a new array and join it later.

var text = '{"employees":[' +
        '{"firstName":"John","lastName":"Doe" },' +
        '{"firstName":"Anna","lastName":"Smith" },' +
        '{"firstName":"Peter","lastName":"Jones" }]}',
    obj = JSON.parse(text);

document.getElementById("demo").innerHTML = obj.employees.map(function (a) {
    return a. firstName + ' ' + a.lastName;
}).join(', ');
<h2>Create Object from JSON String</h2>
<p id="demo"></p>

Upvotes: 2

Related Questions