PTree PTree - 1 month ago 17
Javascript Question

JSON: Showing several values from a string

I'm new with JSON and Javascript. I'm trying to figure out how to print all of these and not just one of them?

<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[1].firstName + " " + obj.employees[1].lastName;
</script>

Answer

I'm sorry to duplicate @Davids answer, but a bit more to output all - add something like out variable to collect all the values and then output them:

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

var obj = JSON.parse(text);
for(var i=0; i < obj.employees.length; i++ ) {

    out+=obj.employees[i].firstName + " " + obj.employees[i].lastName+'<br>';

}

document.getElementById("demo").innerHTML = out;