简体   繁体   English

如何解析这个 JSON 块?

[英]How can one parse this JSON block?

I am working the TinCan API which is sending non-json objects as a JSON request.我正在使用 TinCan API,它将非 json 对象作为 JSON 请求发送。

An example of the Request Payload in said request :所述请求中的请求有效负载示例:

AWSAccessKeyId=secret
&Authorization=secret
&activityId=61XkSYC1ht2%5Fcourse%5Fid
&Expires=1395864543
&Content%2DType=application%2Fjson
&actor=null
&registration=760e3480%2Dba55%2D4991%2D94b0%2D01820dbd23a2
&stateId=resume
&Signature=ZNYa7WTtO5rWx%2FAs%2FuFxTQkiYdc%3D

Their documentation explains in a paraphrased form that "The data is being sent as described in section 7.8 Cross Origin Requests of the XAPI spec, where all headers and content are being included as form parameters."他们的文档以释义的形式解释“数据正在按照 XAPI 规范的第 7.8 节跨源请求中的描述发送,其中所有标头和内容都作为表单参数包含在内。”

Which you can see is true from the Content key in the example above.您可以从上面示例中的Content键中看到这一点。 That key and its children can be decoded and be parsed as JSON.该密钥及其子项可以被解码并解析为 JSON。

But because the initial request is application/json , my app runs into a JSON parse error.但是因为初始请求是application/json ,我的应用程序遇到了 JSON 解析错误。

That being said, is there some way to set up the server, or my controllers to accept these CORS requests so that I can properly parse them and use their information?话虽如此,是否有某种方法可以设置服务器或我的控制器来接受这些 CORS 请求,以便我可以正确解析它们并使用它们的信息?

If you're up against the wall and have no way of changing the completely broken client, you might want to try and gracefully recover here.如果您遇到困难并且无法更改完全损坏的客户端,您可能想尝试在这里优雅地恢复。

Usually you can add a filter in your config.ru file for your application that will re-write the damaged headers:通常,您可以在config.ru文件中为您的应用程序添加一个过滤器,以重写损坏的标头:

use TinCanFixer

Then you write a Rack handler :然后你编写一个Rack 处理程序

class TinCanFixer
  def initialize(app)
    @app = app
  end

  def call(env)
    case (env["CONTENT_TYPE"])
    when "application/json"
      # Check that it's actually JSON
      unless (env["rack.input"].match(/^\{\[/))
        env["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
      end
    end

    @app.call(env)
  end
end

Untested but should, in principle, sniff out non-JSON content and reassign the rack.input header which dictates content type.未经测试,但原则上应该嗅出非 JSON 内容并重新分配指示内容类型的rack.input标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM