Reputation: 6138
I have an API which sends data to a javascript which then throws the response into some input fields.
I wonder if I need to use htmlspecialchars on the json_encode? Like so:
json_encode(
array(
'some_text' => htmlspecialchars('Some special & characters'),
'maybe_html' => htmlspecialchars('some <b>html</b>'),
'etc' => htmlspecialchars('yo')
)
);
Upvotes: 1
Views: 2026
Reputation: 522500
Certainly not. HTML entities make no difference or sense within JSON, and if the result is processed by Javascript and inserted into the document via the DOM API via appropriate methods, then escaping is not needed there either. Escaping should be done when data comes in contact with a specific output medium. Here the data must be correctly encoded as JSON (which json_encode
does), HTML is nowhere to be found here. If anything, HTML escaping should be done in Javascript because it's closer to the HTML, but again, it's unnecessary since Javascript interacts with the DOM API and not HTML.
See The Great Escapism (Or: What You Need To Know To Work With Text Within Text)
Upvotes: 3
Reputation: 12322
Depends on what you're doing with the string data.
What is important is the correct header for the content type.
header('Content-type: application/json');
Upvotes: 2