ExpressJS从嵌套的JSON对象中获取值

时间:2015-06-13 17:05:49

标签: json

我正在使用ExpressJS ..当试图从req.body中获取值时,在console.log(req.body [ndx])中(它打印{" c o .....喜欢这个作为单个字符)

for (var ndx in req.body){
    console.log(req.body[ndx]);
}

我的req.body有以下嵌套的JSON对象:如何提取计数? req.body [" count"]输出undefined

{"count":1,"totalCount":38,"node":[{"categories":[],"foreignSource":null,"foreignId":null,"label":"172.20.96.20","assetRecord":{"description":null,"operatingSystem":null,"category":"Unspecified","password":null,"id":2655,"username":null,"vmwareManagedEntityType":null,"vmwareManagementServer":null,"numpowersupplies":null,"hdd6":null,"hdd5":null,"hdd4":null,"hdd3":null,"hdd2":null,"hdd1":null,"storagectrl":null,"thresholdCategory":null,"enable":null,"connection":null,"autoenable":null,"cpu":null,"ram":null,"snmpcommunity":null,"rackunitheight":null,"admin":null,"additionalhardware":null,"inputpower":null,"vmwareManagedObjectId":null,"vmwareState":null,"vmwareTopologyInfo":null,"circuitId":null,"assetNumber":null,"rack":null,"slot":null,"region":null,"division":null,"department":null,"building":null,"floor":null,"room":null,"vendorPhone":null,"manufacturer":null,"vendor":null,"modelNumber":null,"supportPhone":null,"maintcontract":null,"maintContractNumber":null,"maintContractExpiration":null,"displayCategory":null,"notifyCategory":null,"pollerCategory":null,"vendorFax":null,"vendorAssetNumber":null,"lastModifiedBy":"","lastModifiedDate":1433277477504,"dateInstalled":null,"lease":null,"leaseExpires":null,"managedObjectInstance":null,"managedObjectType":null,"serialNumber":null,"port":null,"comment":null},"lastCapsdPoll":1433277477793,"createTime":1433277477504,"labelSource":"A","type":"A","id":"10"}]}

我的代码:

var bodyParser = require('body-parser'); 
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use('/index', function(req, res, next){
        var getReq = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            jsnArry += chunk; 
         });     
        res.on('end', function (chunk) {         
                req.body = jsnArry;
            for (var ndx in req.body){
                console.log(req.body[ndx]);
            }
            next();
        });
        }).end();
});
app.use(bodyParser.json({ type: 'application/*+json' }));   

app.use('/index', urlencodedParser, function(req, res, next){
    res.send(req.body);
     next();
});

console.log(JSON.parse(req.body))o / p低于

{ count: 1,
  totalCount: 38,
  node:
   [ { categories: [],
       foreignSource: null,
       foreignId: null,
       label: '172.20.96.20',
       assetRecord: [Object],
       lastCapsdPoll: 1433277477793,
       createTime: 1433277477504,
       labelSource: 'A',
       type: 'A',
       id: '10' } ] }

var options = {
          host: host,
          method: 'GET',
          headers: {
              'Accept' : 'application/json'
          }
    };

res.json(info["totalCount"]);
res.sendFile(path.join(_dirname, '/html', 'index.html'));

//仅显示res.json值而不是html页面

以下是我的html文件:

<!DOCTYPE html>
<html data-ng-app="shopStore">
<head>
<meta charset="ISO-8859-1">
<title>Simple Angular Testing</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"></link>
<link rel="stylesheet" type="text/css" href="css/main.css"></link>
</head>
<body>
    <script type="text/javascript" src="js/lib/angular.min.js"></script>
    <script type="text/javascript" src="js/lib/d3.min.js"></script>
    <script type="text/javascript" src="js/product.js"></script>
    <script type="text/javascript" src="js/app.js"></script>

    <div data-ng-controller="scopeCtrl">
        <div data-ng-repeat="x in newRec"> 
            <p>I am product seller {{x.Name}} in {{x.City}} @ {{x.Country}}</p>
        </div>
        {{newRec[0].Name}}  
    </div>

    <div data-ng-controller="nmsCtrl">
     <p>Data to display</p>
    <!--    <div data-ng-repeat="jsn in jsnData"> 
            <p>I am product seller {{jsn.count}} displayed out of {{jsn.totalCount}}</p>
        </div> -->
    </div>  

    <div data-ng-controller="Store-Controller as store">
      <div data-ng-repeat="product in store.products">
        <div data-ng-hide='product.cantPur'>
            <h6>Product:::{{product.item}}</h6>
            <h6>Dollar Price:::{{product.dollar | currency}}</h6>
            <h6>Description::::{{product.desc}}</h6>
            <h6>{{review.stars}}</h6>
            <button data-ng-show='product.canAdd'>Add to Cart</button>
            <product-panel></product-panel>
        </div>
       </div>
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您是否包含body-parsing middlewarebody-parser支持JSON解析。

var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());

bodyParser.json也希望以application/json内容类型接收有效负载。使用jQuery ajax的示例:

.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(){
    ...
  }
})

答案 1 :(得分:0)

您可能需要使用

将req.body转换为json
bar myRes= JSON.parse(req.body);
console.log(myRes.count);

这应该自动为您完成。你的bodyParser中间件如何设置uup?

应该按照下一篇文章进行设置。