我收到错误: [object Object],[object Object],[object Object]。
我希望显示如下完整数组: 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>
&#13;
答案 0 :(得分:2)
您可以使用Array#map
并构建一个新数组并稍后加入。
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(', ');
&#13;
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
&#13;
答案 1 :(得分:0)
你的数组是一个对象数组 - 你需要做更多的编码才能得到你想要的 - 考虑使用Array#map,然后使用Array#join来根据需要格式化输出
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(', ');
了解ES2015的完整性
document.getElementById("demo").innerHTML = obj.employees.map(emp => emp.firstName + ' ' + emp.lastName).join(', ');
答案 2 :(得分:0)
如果要打印所有名称,可以这样做, 如果要从外部文件加载JSON,则必须将JSON文件保存在系统上的其他位置,并且可以使用$ .getJSON加载它,如下所示
String
&#13;
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 + ",";
}
});
&#13;