I have an Ajax call that returns a json hash including errors if anything goes wrong. Here's an example:
{"success":false,"errors":{"image":["file must be at least 1024x768px in size."]},"content_type":"text/json"}
Based on this question I was able to figure out that I could print part of this hash like so:
JSON.stringify( responseJSON.errors )
However this still prints as a code hash, like: {"image":["file must be at least 1024x768px in size."]}
I would really like to convert this to simply:
Image file must be at least 1024x768px in size.
Short of using .replace
after stringify
, is there a straightforward way to do this? Note that the errors hash could contain more errors, for instance:
{"image":["file must be at least 1024x768px in size."],"file":["type is invalid, must be jpg, png, or gif"]}
Update: I don't know why, but none of the functions shown below would return a string when passed the responseJSON
object. However, appending directly to the DOM using jQuery did work. Here's what I ended up doing:
// In the middle of an ajax callback
$('.qq-upload-failed-text:last').append(': <span class="explanation"></span>');
formatErrors( responseJSON );
// As a stand-alone function so it can be reused
function formatErrors( response ) {
$.each( response.errors, function(key, value) {
$('span.explanation:last').append( key + " " + value );
});
}
Why that would insert the text correctly into the dom but using Dampsquid's function or any of the others would only return an empty string is beyond me.