Skip to content Skip to sidebar Skip to footer

Putting Html In Json

As per title, is it considered a good practice to put HTML in JSON? The reason I need to do this is because I would like to have a custom dropdown where the list is coming from the

Solution 1:

You wouldn't be the first to do it, and certainly not the last.

To really answer the question, assuming you're following the protocol/standard and not breaking it (including quotes in the string without escaping them, for instance) you should be fine. json_encode does a great job at all this, but as @Kolink mentioned make sure you encode it to UTF8 first otherwise stray Unicode characters will occasionally break it resulting in empty output.

Beyond that, it's programmer preference to use it. Some avoid it and keep the UI work on the page, others have the server generate the UI and let JavaScript just dump it--either way it's your call, and perfectly acceptable.

Solution 2:

There's nothing wrong with it. json_encode escapes all characters anyway, so the only thing you have to beware of is make sure your strings are utf8_encoded.

Solution 3:

You could, sure, but you could just as easily pass the values as an array in the JSON and put the HTML rendering code in the client; saving you server cycles, bandwidth bytes, and logic-presentation blending.

Post a Comment for "Putting Html In Json"