根据查询字符串过滤json数据

时间:2013-05-05 15:05:40

标签: jquery json

我正在学习json,当我需要展示其工作是记者的人时,我迷失了过滤json数据。

 {
"person": [
   {
       "firstName": "Clark",
       "lastName": "Gable",
       "job": "Reporter",
       "roll": 20
   },
   {
       "firstName": "Bruce",
       "lastName": "Willis",
       "job": "Playboy",
       "roll": 30
   },
   {
       "firstName": "James",
       "lastName": "Parker",
       "job": "Reporter",
       "roll": 40
   }
]
}

使用查询字符串调用页面我使用job_param作为另一个函数的变量

http://jsontest/person.html?job=reporter



var job_param = gup( 'job' );
alert("job selected is: " + job_param);


$(function() {
var people = [];
$.getJSON('people.json', function(data) {
   $.each(data.person, function(i, f) {
      var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
   "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "<td><a href=\"category.html?cat=" + f.firstName + "\">Go</a>" + "</td>" + "</tr>"
       $(tblRow).appendTo("#userdata tbody");
 });

});

});

html文件

<table id= "userdata" border="2">
<thead>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Job</th>
        <th>City</th>
        <th>Go</th>
    </thead>
  <tbody>

   </tbody>
 </table>

我可以从mysql生成一个新的json文件,只显示列表中的记者,但我认为不应该这样做。感谢。

3 个答案:

答案 0 :(得分:0)

您可以添加以下内容:

$(function() {
var people = [];
$.getJSON('people.json', function(data) {
   $.each(data.person, function(i, f) {
      if(f.job=='Reporter')
      {
      var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
      "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "<td><a href=\"category.html?cat=" + f.firstName + "\">Go</a>" + "</td>" + "</tr>"
       $(tblRow).appendTo("#userdata tbody");
         });
      }

    });

});

答案 1 :(得分:0)

首先获取查询字符串值:

var job = GetQueryStringValue('job');

然后将json与变量进行比较:

$.each(data.person, function (key, value) {
    console.log(key + ": " + value.firstName);
    if (value.job == job) {
        // If person reporter, do this
    } else {
        // If person is not a reporter, do this
    }
});

答案 2 :(得分:0)

Javascript库“下划线”http://underscorejs.org/#filter有很好的工具可以过滤linke:

reporters = _.filter(array_of_people, function(p){ return p.job == "Reporter"; });

这是一个小提琴: http://jsfiddle.net/bjelline/sXfxD/