0

I'm trying to return an html snippet from a service that can only return valid JSON.

I've tried some things like:

This gets me a bunch of character like \n\n\n\n\t\t\t\t

return JSON.stringify({html: $('body').html()});

or

return JSON.stringify($('body').html());

On the receiving end, I'd like to be able to parse that HTML via Cheerio, or jQuery or JSDom so I can then run queries like $(".some_selector") on that data.

What is the proper way of doing this? Any special libraries / methods that can handle the escaping for me? I've googled it, but haven't had any clear results...

Thanks.

Jamis Charles
  • 5,827
  • 8
  • 32
  • 42
  • Perhaps this would help? [Escaping HTML strings with jQuery][1] [1]: http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery – iansltx Jun 18 '13 at 16:43

2 Answers2

0

On the receiving end, you need to simply undo the JSON serialization. That's it!

Your HTML will be in its regular format at obj.html, which you can then parse with whatever DOM parser you want.

Brad
  • 159,648
  • 54
  • 349
  • 530
0

Well, you are probably going to need to worry about quotes in the HTML (like with attributes) because the could interfere with the quotes that delimit your JSON values.

Here is similar question as well as this web page that explains some of what you need to consider.

Briefly looking at npmsj.org, I didn't see any reputable modules that might help you make HTML JSON compatible, but I think you can probably figure it out fairly easily on your own, given a large enough sample set of HTML. You can always run your JSON through this validator to check it. I suppose you could also simply do a JSON.parse(jsonContainingHtml) on it as well. You'll get an exception if the string is not valid JSON.

Community
  • 1
  • 1
d512
  • 32,267
  • 28
  • 81
  • 107