如何使用node.js解析文本中的JSON文件?

时间:2014-07-30 03:23:32

标签: javascript json node.js express

所以我试图将一个html响应解析为JSON以获取可访问的对象。

这是我的路由器

router.get('/yammer', function(req, res) {
  var userFields;
  var yammerCode = req.query.code;
  var getYammerFieldsAddress = "http://www.yammer.combalwh;eoiahweg";
  getYammerFieldsAddress += yammerCode;
  console.log(getYammerFieldsAddress);
  httpreq.get(getYammerFieldsAddress, function(err, response) {
    if (err) return console.log(err);
    console.log(response);
    var yammerUserInfo = response.body;


    var blah = yammerUserInfo.user;
    console.log(blah);

但信息就像这样

{
  "user":
  {
    "timezone": "Hawaii",
    "interests": null,
    "type": "user",
    "mugshot_url": "https://www.yammer.com/yamage-backstage/photos/…",
    "kids_names": null,
    "settings": {
      "xdr_proxy": "https://stagexdrproxy.yammer.com"
    },
    "schools": [],
    "verified_admin": "false",
    "birth_date": "",
    "expertise": null,
    "job_title": "",
    "state": "active",
    "contact": {
      "phone_numbers": [],
      "im": {
        "provider": "",
        "username": ""
      },
      "email_addresses": [
        {
          "type": "primary",
          "address": "test@yammer-inc.com"
        }
      ]
    },
    "location": null,
    "previous_companies": [],
    "hire_date": null,
    "admin": "false",
    "full_name": "TestAccount",
    "network_id": 155465488,
    "stats": {
      "updates": 2,
      "followers": 0,
      "following": 0
    },
    "can_broadcast": "false",
    "summary": null,
    "external_urls": [],
    "name": "clientappstest",
    "network_domains": [
      "yammer-inc.com"
    ],
    "network_name": "Yammer",
    "significant_other": null,
    "id": 1014216,
    "web_url": "https://www.yammer.com/yammer-inc.com/users/…",
    "url": "https://www.yammer.com/api/v1/users/101416",
    "guid": null
  },
  "access_token": {
    "view_subscriptions": true,
    "expires_at": null,
    "authorized_at": "2011/04/06 16:25:46 +0000",
    "modify_subscriptions": true,
    "modify_messages": true,
    "network_permalink": "yammer-inc.com",
    "view_members": true,
    "view_tags": true,
    "network_id": 155465488,
    "user_id": 1014216,
    "view_groups": true,
    "token": "ajsdfiasd7f6asdf8o",
    "network_name": "Yammer",
    "view_messages": true,
    "created_at": "2011/04/06 16:25:46 +0000"
  },

所以似乎有多个对象通过。我已经尝试从响应主体访问它们,我也尝试过JSON.stringify(),但我无法访问它。有任何想法吗?谢谢!

2 个答案:

答案 0 :(得分:0)

尝试

var jsonObject = JSON.parse(response.body);

答案 1 :(得分:0)

替换此行

var yammerUserInfo = response.body;

使用

var yammerUserInfo = JSON.parse(response.body);

它应该正常工作。 :)