从JSON对象检索键值对 - Node JS

时间:2016-08-18 10:51:46

标签: ajax node.js

从前端我将JSON array传递给我的Node JS后端。现在,我需要检索JSON array并阅读其key-value对并将其打印在console中。我怎样才能做到这一点。

代码如下:

JQUERY

$( "#send" ).submit(function( event ) {    
  var dict = {};
  $("input[name=name]").each(function (i) {
    dict[$(this).val()] = $('input[name=age]').eq(i).val();
  });

  someObject=JSON.stringify(dict, null, 2);

 $.ajax({
   url: "food/newpage",
   type: "POST",
   dataType: "json",
   data: { dataobj: someObject },
 });
});

NODE JS

router.post('/newpage', function (req, res, next) {    
  console.log('print ' + req.body.dataobj);

  for(var attributename in req.body.dataobj){
    console.log(attributename+": "+req.body.dataobj[attributename]);
  }

  res.render('food/newpage');
});

当我打印req.body.dataobj时,我得到以下输出:

{
  "sam": "five",
  "Alex": "fifteen",   
  "Matt": "Two",   
}

我的问题是:我需要检索JSON数组并将其打印在console.log key is equal to the namevalue is equal to the age中。我怎样才能做到这一点 ?

输出 - 更新

  

key = 0且value = {0 = {key = 1 and value =

     

1 =

     

key = 2且value = 2 = key = 3且value = 3 = key = 4且value =“   4 =“key = 5,value = s 5 = s key = 6,value = f 6 = f key = 7和value   = d 7 = d key = 8且value = s 8 = s key = 9且value = f 9 = f key = 10且value =“10 =”key = 11且value =:11 =:key = 12且值= 12 =键=   13和value =“13 =”key = 14,value = a 14 = a key = 15,value = d   15 = d key = 16,value = f 16 = f key = 17,value = d 17 = d key = 18和   value =“18 =”key = 19,value =

     

19 =

     

key = 20 and value =} 20 =}

3 个答案:

答案 0 :(得分:0)

你可以试试这个,我没试过,但你会得到结果。

Jquery的

$( "#send" ).submit(function( event ) {    
var dict = {};
$("input[name=name]").each(function (i) {
 dict[$(this).val()] = $('input[name=age]').eq(i).val();
});

$.ajax({
 url: "food/newpage",
 type: "POST",
 dataType: "json",
 data: { dataobj: someObject },
});
});

节点js

router.post('/newpage', function (req, res, next) {

console.log('print ' + req.body.dataobj);

for(var k in req.body.dataobj){
console.log("key= "+ k + " and value ="+ req.body.dataobj[k] );
console.log(k + "="+ req.body.dataobj[k]);
 }

res.render('food/newpage');

});

答案 1 :(得分:0)

在使用之前,您必须将dataobj解析为json对象,如下所示

router.post('/newpage', function (req, res, next) {

console.log('print ' + req.body.dataobj);

**req.body.dataobj = JSON.parse(req.body.dataobj)**

for(var attributename in req.body.dataobj){
  console.log("key= "+ attributename.name + " and value ="+ attributename.age);
  console.log(attributename.name + "="+ attributename.age  +);
 }
res.render('food/newpage');

});

答案 2 :(得分:0)

您可以通过使用括号表示法索引对象文字来获得所需的条目(例如“Alex”)

var age = req.body.dataobj["Alex"]
if (age > ...) { ... }

然后检查年龄是否符合您的标准。

只是为了纠正你一点:你实际上是向后端发送对象文字{ a: b }),而不是数组([a, b])。