Encoding HTML in JSON

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

Encoding HTML in JSON

Post by mintedjo »

Hi Thar!

I'm in the middle of doing something and for testing purposes i want to hard code a variable in JSON and decode it with json_decode(). I'm having trouble encoding the JSON because it contains HTML tags and i just can't figure out how to make it work. Heres what i've tried with an example of a table containing one cell. Feel free to explain all the reasons why each one is syntactically incorrect, I'll do my best to explain what I think...

Code: Select all

 
// The single backslash means that the ones around html attribute values terminate the string when it is parsed
$JSON = "{\"table\": \"<tbody><tr><td colspan=\"2\" rowspan=\"2\"></td></td></tr></tbody>\"}";
 
// No idea why this one doesnt work, I figured the triple backslash would work as a double escape but that fails too
$JSON = "{\"table\": \"<tbody><tr><td colspan=\\\"2\\\" rowspan=\\\"2\\\"></td></td></tr></tbody>\"}";
 
// I guess this fails because json_decode only likes strings defined with double quotes not single ones
$JSON = '{\"table\": \"<tbody><tr><td colspan=\\\"2\\\" rowspan=\\\"2\\\"></td></td></tr></tbody>\"}';
Ok well thats all i could think of. Any feedback is much appreciated cos I can't do it :-(
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Encoding HTML in JSON

Post by kaszu »

All you examples works for me (json_decode second argument must be set)

Code: Select all

$JSON = "{\"table\": \"<tbody><tr><td colspan=\"2\" rowspan=\"2\"></td></td></tr></tbody>\"}";
print_r(json_decode($JSON, true));
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Encoding HTML in JSON

Post by John Cartwright »

Are we against using json_encode?

Code: Select all

$json = json_encode(array('table' => '<tbody><tr><td colspan="2" rowspan="2"></td></td></tr></tbody>'));
mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

Re: Encoding HTML in JSON

Post by mintedjo »

Its ok guys i fixed it.
Thanks very much for responding :-)

I reached a stage where I could no longer tolerate it and wrote the whole javascript thing to make the string in a real context and send that to the server.
Post Reply