[英]Convert html response to json
I am trying to implement SMS API in rails, when I hit the API url I get following html response: 我试图在rails中实现SMS API,当我点击API网址时,我得到了以下html响应:
<!DOCTYPE RESULT SYSTEM "http: api_link ">
<html><body>
<result reqid="57469">
<mid submitdate="2015-12-02 00:51:55" id="1" tag="null" tid="103335">
</mid>
</result>
</body></html>
How can I convert this to json
? 如何将其转换为
json
?
Unfortunately at this time you cannot convert html straight to json, but you can convert html to a hash and then the hash to json. 不幸的是,此时您无法将html直接转换为json,但可以将html转换为哈希,然后将哈希转换为json。
YOUR_HTML_CODE = '<!DOCTYPE RESULT SYSTEM "http: api_link "><html><body> <result reqid="57469"> <mid submitdate="2015-12-02 00:51:55" id="1" tag="null" tid="103335"> </mid></result></body></html>'
@data = Hash.from_xml(YOUR_HTML_CODE).to_json
Returns: 返回:
=> "{\"html\":{\"body\":{\"result\":{\"reqid\":\"57469\",\"mid\":{\"submitdate\":\"2015-12-02 00:51:55\",\"id\":\"1\",\"tag\":\"null\",\"tid\":\"103335\",\"__content__\":\"\\n\\n \"}}}}}"
To find more ways to do what you want, search for rails xml to json, you will find more answers on this question . 要找到更多方法来完成您想要的事情,请将Rails xml搜索为json,您将找到有关此问题的更多答案。 Crack gem seems to be excellent for this.
裂纹宝石似乎对此非常好。
Note that if you are using rails you should be handling this on the backend, but that was not as helpful of an answer by itself, thus my answer above. 请注意 ,如果您使用的是Rails,则应该在后端处理此问题,但这本身对回答的帮助并不那么有用,因此我的回答也没有帮助。
If your api only returns json
you can set format resource. 如果您的api仅返回
json
,则可以设置格式资源。
Example: 例:
config/routes.rb 配置/ routes.rb中
Rails.application.routes.draw do
resources :posts, defaults: { format: :json }
end
If your api returns html
, xml
,and json
you can set in your controller(remove defaults: { format: :json }
in config/routes.rb
): 如果您的api返回
html
, xml
和json
,则可以在控制器中进行defaults: { format: :json }
(删除defaults: { format: :json }
config/routes.rb
defaults: { format: :json }
):
app/controller/posts_controller.rb 应用程序/控制器/ posts_controller.rb
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @post }
format.json { render :json => @post }
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.