Convert html to json

advertisements

I am trying to implement SMS API in rails, when I hit the API url I am able to get following html response:

<!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>

Now all I want is to convert this data to json. Please help me! I am new to rails.


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.

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. 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.