如何对URL进行JSON调用?

Har*_*ldo 42 javascript json

我正在查看以下API:

http://wiki.github.com/soundcloud/api/oembed-api

他们给出的例子是

呼叫:

http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json
Run Code Online (Sandbox Code Playgroud)

响应:

{
"html":"<object height=\"81\" ... ",
"user":"Forss",
"permalink":"http:\/\/soundcloud.com\/forss\/flickermood",
"title":"Flickermood",
"type":"rich",
"provider_url":"http:\/\/soundcloud.com",
"description":"From the Soulhack album...",
"version":1.0,
"user_permalink_url":"http:\/\/soundcloud.com\/forss",
"height":81,
"provider_name":"Soundcloud",
"width":0
}
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能从一个网址获取这个JSON对象?

Jam*_*mes 59

它们似乎js为format参数提供了一个选项,它将返回JSONP.您可以像这样检索JSONP:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  
Run Code Online (Sandbox Code Playgroud)

  • 这个答案最初让我感到困惑,因为帖子标题是JSON,我没有立刻意识到这个代码示例返回JSONP,它根本不是JSON(因此不会读取格式正确的JSON.)下面的答案来自@DickFeynman的应该超过这个,它完美无缺.这是一个显示JSON和JSONP之间差异的教程:https://web.archive.org/web/20160114013014/http://json-jsonp-tutorial.craic.com/index.html (4认同)
  • 现代用户请注意:请注意此答案中非常旧的日期。由于现代浏览器的安全功能,这不再有效。截至撰写本文时,在 Chrome 中,它会导致 CORB(不,不是 CORS)错误。 (3认同)

小智 52

标准的http GET请求应该这样做.然后,您可以使用JSON.parse()将其转换为json对象.

function Get(yourUrl){
    var Httpreq = new XMLHttpRequest(); // a new request
    Httpreq.open("GET",yourUrl,false);
    Httpreq.send(null);
    return Httpreq.responseText;          
}
Run Code Online (Sandbox Code Playgroud)

然后

var json_obj = JSON.parse(Get(yourUrl));
console.log("this is the author name: "+json_obj.author_name);
Run Code Online (Sandbox Code Playgroud)

基本上就是这样

  • 这不是同步请求.恕我直言,这些都是一个坏主意,可以占据整个网站.最好以异步方式加载它们并传递成功函数. (3认同)
  • 给定的URI在另一个域上,因此,除非外部服务器发送CORS标头,否则正常的AJAX请求将不起作用。 (2认同)

SLa*_*aks 11

由于该URL与您的网站不在同一个域中,因此您需要使用JSONP.

例如:(在jQuery中):

$.getJSON(
    'http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', 
    function(data) { ... }
);
Run Code Online (Sandbox Code Playgroud)

这可以通过创建这样的<script>标记来实现:

<script src="http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=someFunction" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

然后他们的服务器发出Javascript,调用someFunction要检索的数据.
`someFunction是由jQuery生成的内部回调,然后调用你的回调.


Nic*_*ons 9

在现代 JS 中,您可以通过fetch()在 URL 上调用 ES6 来获取 JSON 数据,然后使用 ES7从 fetch 中async/await“解压”响应对象以获取 JSON 数据,如下所示:

const getJSON = async url => {
  const response = await fetch(url);
  if(!response.ok) // check if response worked (no 404 errors etc...)
    throw new Error(response.statusText);

  const data = await response.json(); // get JSON from the response
  return data; // returns a promise, which resolves to this data value
}

console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json").then(data => {
  console.log(data);
}).catch(error => {
  console.error(error);
});
Run Code Online (Sandbox Code Playgroud)

如果忽略异常/错误处理,上述方法可以简化为几行(通常不推荐,因为这会导致不必要的错误):

const getJSON = async url => {
  const response = await fetch(url);
  return response.json(); // get JSON from the response 
}

console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json")
  .then(data => console.log(data));
Run Code Online (Sandbox Code Playgroud)


小智 7

DickFeynman的答案是一个可行的解决方案,适用于JQuery不适合的任何情况,或者不是必需的.正如ComFreek所说,这需要在服务器端设置CORS头.如果这是您的服务,并且您可以处理更大的安全问题,那么这是完全可行的.

下面是Flask服务的列表,设置CORS标头,从数据库中获取数据,使用JSON进行响应,以及在客户端使用DickFeynman的方法快乐地工作:

#!/usr/bin/env python 
from __future__ import unicode_literals
from flask      import Flask, Response, jsonify, redirect, request, url_for
from your_model import *
import os
try:
    import simplejson as json;
except ImportError:
    import json
try:
    from flask.ext.cors import *
except:
    from flask_cors import *

app = Flask(__name__)

@app.before_request
def before_request():
try:
    # Provided by an object in your_model
    app.session = SessionManager.connect()
except:
    print "Database connection failed."

@app.teardown_request
def shutdown_session(exception=None):
    app.session.close()

# A route with a CORS header, to enable your javascript client to access 
# JSON created from a database query.
@app.route('/whatever-data/', methods=['GET', 'OPTIONS'])
@cross_origin(headers=['Content-Type'])
def json_data():
    whatever_list = []
    results_json  = None
    try:
        # Use SQL Alchemy to select all Whatevers, WHERE size > 0.
        whatevers = app.session.query(Whatever).filter(Whatever.size > 0).all()
        if whatevers and len(whatevers) > 0:
            for whatever in whatevers:
                # Each whatever is able to return a serialized version of itself. 
                # Refer to your_model.
                whatever_list.append(whatever.serialize())
             # Convert a list to JSON. 
             results_json = json.dumps(whatever_list)
    except SQLAlchemyError as e:
        print 'Error {0}'.format(e)
        exit(0)

    if len(whatevers) < 1 or not results_json:
        exit(0)
    else:
        # Because we used json.dumps(), rather than jsonify(), 
        # we need to create a Flask Response object, here.
        return Response(response=str(results_json), mimetype='application/json')

if __name__ == '__main__':
    #@NOTE Not suitable for production. As configured, 
    #      your Flask service is in debug mode and publicly accessible.  
    app.run(debug=True, host='0.0.0.0', port=5001) # http://localhost:5001/
Run Code Online (Sandbox Code Playgroud)

your_model包含任何内容的序列化方法,以及数据库连接管理器(可以进行一些重构,但足以在较大的系统或模型/视图/控制体系结构中集中创建数据库会话).这恰好使用postgreSQL,但可以轻松使用任何服务器端数据存储:

#!/usr/bin/env python 
# Filename: your_model.py
import time
import psycopg2
import psycopg2.pool
import psycopg2.extras
from   psycopg2.extensions        import adapt, register_adapter, AsIs
from   sqlalchemy                 import update
from   sqlalchemy.orm             import *
from   sqlalchemy.exc             import *
from   sqlalchemy.dialects        import postgresql
from   sqlalchemy                 import Table, Column, Integer, ForeignKey
from   sqlalchemy.ext.declarative import declarative_base

class SessionManager(object):
    @staticmethod
    def connect():
        engine = create_engine('postgresql://id:passwd@localhost/mydatabase', 
                                echo = True)
        Session = sessionmaker(bind = engine, 
                               autoflush = True, 
                               expire_on_commit = False, 
                               autocommit = False)
    session = Session()
    return session

  @staticmethod
  def declareBase():
      engine = create_engine('postgresql://id:passwd@localhost/mydatabase', echo=True)
      whatever_metadata = MetaData(engine, schema ='public')
      Base = declarative_base(metadata=whatever_metadata)
      return Base

Base = SessionManager.declareBase()

class Whatever(Base):
    """Create, supply information about, and manage the state of one or more whatever.
    """
    __tablename__         = 'whatever'
    id                    = Column(Integer, primary_key=True)
    whatever_digest       = Column(VARCHAR, unique=True)
    best_name             = Column(VARCHAR, nullable = True)
    whatever_timestamp    = Column(BigInteger, default = time.time())
    whatever_raw          = Column(Numeric(precision = 1000, scale = 0), default = 0.0)
    whatever_label        = Column(postgresql.VARCHAR, nullable = True)
    size                  = Column(BigInteger, default = 0)

    def __init__(self, 
                 whatever_digest = '', 
                 best_name = '', 
                 whatever_timestamp = 0, 
                 whatever_raw = 0, 
                 whatever_label = '', 
                 size = 0):
        self.whatever_digest         = whatever_digest
        self.best_name               = best_name
        self.whatever_timestamp      = whatever_timestamp
        self.whatever_raw            = whatever_raw
        self.whatever_label          = whatever_label

    # Serialize one way or another, just handle appropriately in the client.  
    def serialize(self):
        return {
            'best_name'     :self.best_name,
            'whatever_label':self.whatever_label,
            'size'          :self.size,
        }
Run Code Online (Sandbox Code Playgroud)

回想起来,我可能将所有对象序列化为列表,而不是Python dict,这可能简化了他们在Flask服务中的处理,我可能在Flask实现中更好地分离了关注点(数据库调用可能不应该是内置的路由处理),但可以改善这一点,一旦你有你自己的开发环境中工作的解决方案.

另外,我并不是建议人们避免使用JQuery.但是,如果JQuery不在图片中,出于某种原因,这种方法似乎是一种合理的选择.

无论如何,它都有效.

这是我在客户端实现DickFeynman的方法:

<script type="text/javascript">
    var addr = "dev.yourserver.yourorg.tld"
    var port = "5001"

    function Get(whateverUrl){
        var Httpreq = new XMLHttpRequest(); // a new request
        Httpreq.open("GET",whateverUrl,false);
        Httpreq.send(null);
        return Httpreq.responseText;          
    }

    var whatever_list_obj = JSON.parse(Get("http://" + addr + ":" + port + "/whatever-data/"));
    whatever_qty = whatever_list_obj.length;
    for (var i = 0; i < whatever_qty; i++) {
        console.log(whatever_list_obj[i].best_name);
    }
</script>
Run Code Online (Sandbox Code Playgroud)

我不会列出我的控制台输出,但我正在查看一长串的whatever.best_name字符串.

更重要的是:whatever_list_obj可用于我的javascript命名空间,无论我关心它做什么,...可能包括使用D3.js生成图形,使用OpenLayers或CesiumJS进行映射,或计算一些中间值没有特别需要住在我的DOM中.