【问题标题】:Parsing JSON response from a http request?解析来自 http 请求的 JSON 响应?
【发布时间】:2016-04-14 19:40:30
【问题描述】:

我正在使用 Nodejs 应用程序中的“请求”模块向站点发出 http 请求并以 JSON 格式返回 html。但是,我正在尝试使用 JSON.parse() 函数,但它似乎不起作用?

我已经在控制台记录了响应以检查请求是否正常工作,它是..但是解析没有返回任何内容?

有什么想法吗?代码:

parse.js

    var requestify = require('requestify');
    var fs = require('fs')
    var obj;

    var url = 'http://www.bbc.co.uk'
    requestify.request(url, {
                    method: 'GET',

                   cookies: {
                     'examplename':'examplevalue'
                    },

                  dataType: 'json'

    })
    .then(function(response){
     var pattern = /href=.{1,50}/g
     obj = JSON.parse('{"filter": "href.+/-", "flags": "g"}')
    obj.filter = new RegExp(obj.filter, obj.flags)
    var r = response.match(obj.filter)
    console.log(r)
    })

【问题讨论】:

    标签: javascript json node.js parsing httprequest


    【解决方案1】:

    仅仅因为请求指定您希望返回 json 并不意味着 bbc 会以 json 响应。看起来 bbc 正在使用 html 进行响应,这使得 JSON.parse 预期失败。

    $ curl -H "Content-Type: application/json" http://www.bbc.co.uk -v > out.log
    * About to connect() to www.bbc.co.uk port 80 (#0)
    *   Trying 212.58.244.71... connected
    * Connected to www.bbc.co.uk (212.58.244.71) port 80 (#0)
    > GET / HTTP/1.1
    > User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8y zlib/1.2.3
    > Host: www.bbc.co.uk
    > Accept: */*
    > Content-Type: application/json
    > 
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
      0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0< HTTP/1.1 200 OK
    < Server: nginx
    < Content-Type: text/html; charset=utf-8
    < ETag: W/"2266d-K1zKA7z5pAya6M49nLj/pg"
    < X-Frame-Options: SAMEORIGIN
    < x-origin-route: xrt-lb
    < Content-Length: 140909
    < Date: Sun, 10 Jan 2016 13:06:27 GMT
    < Connection: keep-alive
    < Set-Cookie: BBC-UID=c566b912a5f755d32356f02df1d767d43a09776757d42496ea40c7c28dc4415c0curl/7.19.7%20(universal-apple-darwin10.0)%20libcurl/7.19.7%20OpenSSL/0.9.8y%20zlib/1.2.3; expires=Thu, 09-Jan-20 13:06:27 GMT; path=/; domain=.bbc.co.uk
    < X-Cache-Action: HIT
    < X-Cache-Hits: 123
    < X-Cache-Age: 9
    < Cache-Control: private, max-age=0, must-revalidate
    < Vary: Accept-Encoding, X-CDN
    

    【讨论】:

    • 将 html 转换为 JSON 的最佳方法是什么?
    • 从 html 中提取数据可以使用像 github.com/cheeriojs/cheerio 这样的库来完成
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    相关资源
    最近更新 更多