JSON:显示字符串中的多个值

时间:2016-10-17 01:29:15

标签: javascript arrays json parsing

我是JSON和Javascript的新手。我试图找出如何打印所有这些而不仅仅是其中一个?

<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>

6 个答案:

答案 0 :(得分:1)

我很遗憾复制@Davids答案,但输出全部更多 - 添加类似out变量的东西来收集所有值,然后输出它们:

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;

答案 1 :(得分:0)

尝试使用for循环,你只是打印索引1的值,也许这样的东西应该起作用

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

obj = JSON.parse(text);
for (var i = 0; i < obj.employees.length; i++) {
  document.getElementById("demo").innerHTML += 
  obj.employees[i].firstName + " " + obj.employees[i].lastName + " ";
}

遍历对象,以便您可以将值添加到元素中:DD希望这有助于

答案 2 :(得分:-1)

您可以循环显示它。

&#13;
&#13;
for (var i = 0; i < obj.employees.length; i++) {
              document.getElementById("demo").innerHTML +=
                        obj.employees[i].firstName + " " + obj.employees[i].lastName;
            }
&#13;
&#13;
&#13;

注意:obj.employees.length = 3(在这种情况下)

答案 3 :(得分:-1)

如果你问我这样做,我会这样做。代码已经过测试。试试吧。我正在使用严格检查的自执行功能。利用javascript的原型性质。我假设您已经解析了JSON数据并且可以使用。如果您需要更多解释,请告诉我。

(function(){
    'use strict';
    var text = {
        employees: [
            {
                firstName:'john',lastName:'Dae'
            },
            {
                firstName:'Anna',lastName:'Smith'
            },
            {
                firstName:'Peter',lastName:'Jones'
            }
        ]
    };

    var Employee = function(data){
    //private vars goes here.
        this.employees = data.employees;
    };
    Employee.prototype.append = function(id_of_element){
        for(var i = 0;i<this.employees.length;i++){
            document.getElementById('demo').innerHTML += '<li>'+this.employees[i].firstName+ ' ' +this.employees[i].lastName+'</li>';
        }
    };

    var emp = new Employee(text);
    emp.append();

})();

答案 4 :(得分:-1)

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

obj = JSON.parse(text);
obj.employees.forEach(function(employee) {
  document.getElementById("demo").innerHTML += employee.firstName + " " + employee.lastName + "\n";
});
<pre id="demo"></pre>

答案 5 :(得分:-1)

为简单起见(但不一定是性能),请使用ES5的数组方法:

import pygame
import sys
import time
from OpenGL.GL import *
from OpenGL.GLU import *

title = "FPS Timer Demo"
target_fps = 60
(width, height) = (300, 200)
flags = pygame.DOUBLEBUF|pygame.OPENGL
screen = pygame.display.set_mode((width, height), flags)

rotation = 0
square_size = 50
prev_time = time.time()

while True:
    #Handle the events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    #Do computations and render stuff on screen
    rotation += 1
    glClear(GL_COLOR_BUFFER_BIT)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, width, 0, height, -1, 1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslate(width/2.0, height/2.0, 0)
    glRotate(rotation, 0, 0, 1)
    glTranslate(-square_size/2.0, -square_size/2.0, 0)
    glBegin(GL_QUADS)
    glVertex(0, 0, 0)
    glVertex(50, 0, 0)
    glVertex(50, 50, 0)
    glVertex(0, 50, 0)
    glEnd()
    pygame.display.flip()

    #Timing code at the END!
    curr_time = time.time()#so now we have time after processing
    diff = curr_time - prev_time#frame took this much time to process and render
    delay = max(1.0/target_fps - diff, 0)#if we finished early, wait the remaining time to desired fps, else wait 0 ms!
    time.sleep(delay)
    fps = 1.0/(delay + diff)#fps is based on total time ("processing" diff time + "wasted" delay time)
    prev_time = curr_time
    pygame.display.set_caption("{0}: {1:.2f}".format(title, fps))

或ES6语法:

document.getElementById('demo').innerHTML =
     obj.employees.map(function(employee) {
         return employee.firstName + ' ' + employee.lastName;
     }).join('<br>');

请注意上述两种情况如何避免重复解除引用document.getElementById('demo').innerHTML = obj.employees.map(employee => employee.firstName + ' ' + employee.lastName) .join('<br>');

注意:这不会在最终名称后加obj.employees[i],但如果重要的话,你应该把你的名单放在&#34;块样式&#34;元素将隐含地移动到最后一行为你。