Home  >  Article  >  Web Front-end  >  Simple implementation method of converting JS JSON object to string_javascript skills

Simple implementation method of converting JS JSON object to string_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:14:371282browse

Since IE6 and 7 do not support JSON.stringify(json), we have to write another function to replace this method. The code is as follows:

Copy code The code is as follows:

function JsonToStr(o) {
var arr = [];
var fmt = function(s) {
if ( typeof s == 'object' && s != null) return JsonToStr(s);
return /^(string|number)$/.test(typeof s) ? "'" s "'" : s;
}
for (var i in o) arr.push("'" i "':" fmt(o[i]));
return '{' arr.join(',') ' }';
}

In addition: If you don’t want the numbers in json to be stringified. You can modify it:

return /^(string|number)$/.test(typeof s) ? '"' s '"' : s;

is: return /^(string)$/.test(typeof s) ? '"' s '"' : s;

(In fact, just ignore the number type)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn