您好,登录后才能下订单哦!
JSON.stringify() 方法是将一个JavaScript值(对象或者数组)转换为一个 JSON字符串,如果指定了replacer是一个函数,则可以选择性的替换值,或者如果指定了replacer是一个数组,可选择性的仅包含数组指定的属性。
语法
JSON.stringify(value[, replacer [, space]])
参数
value
将要序列化成 一个JSON 字符串的值。
replacer 可选
如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为null或者未提供,则对象所有的属性都会被序列化;关于该参数更详细的解释和示例,请参考使用原生的 JSON 对象一文。
space 可选
指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数为字符串(字符串的前十个字母),该字符串将被作为空格;如果该参数没有提供(或者为null)将没有空格。
返回值
一个表示给定值的JSON字符串。
描述
JSON.stringify()将值转换为相应的JSON格式:
实例
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify("foo"); // '"foo"'
JSON.stringify([1, "false", false]); // '[1,"false",false]'
JSON.stringify({ x: 5 }); // '{"x":5}'
JSON.stringify({x: 5, y: 6});
// "{"x":5,"y":6}"
JSON.stringify([new Number(1), new String("false"), new Boolean(false)]);
// '[1,"false",false]'
JSON.stringify({x: undefined, y: Object, z: Symbol("")});
// '{}'
JSON.stringify([undefined, Object, Symbol("")]);
// '[null,null,null]'
JSON.stringify({[Symbol("foo")]: "foo"});
// '{}'
JSON.stringify({[Symbol.for("foo")]: "foo"}, [Symbol.for("foo")]);
// '{}'
JSON.stringify(
{[Symbol.for("foo")]: "foo"},
function (k, v) {
if (typeof k === "symbol"){
return "a symbol";
}
}
);
// undefined
// 不可枚举的属性默认会被忽略:
JSON.stringify(
Object.create(
null,
{
x: { value: 'x', enumerable: false },
y: { value: 'y', enumerable: true }
}
)
);
// "{"y":"y"}"
replacer参数
replacer参数可以是一个函数或者一个数组。作为函数,它有两个参数,键(key)值(value)都会被序列化。
注意: 不能用replacer方法,从数组中移除值(values),如若返回undefined或者一个函数,将会被null取代。
例子(function)
function replacer(key, value) {
if (typeof value === "string") {
return undefined;
}
return value;
}
var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer);
JSON序列化结果为 {"week":45,"month":7}.
例子(array)
如果replacer是一个数组,数组的值代表将被序列化成JSON字符串的属性名。
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', 只保留“week”和“month”属性值。
space 参数
space 参数用来控制结果字符串里面的间距。如果是一个数字, 则在字符串化时每一级别会比上一级别缩进多这个数字值的空格(最多10个空格);如果是一个字符串,则每一级别会比上一级别多缩进用该字符串(或该字符串的前十个字符)。
JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'
使用制表符(\t)来缩进:
JSON.stringify({ uno: 1, dos : 2 }, null, '\t')
// '{ \
// "uno": 1, \
// "dos": 2 \
// }'
toJSON 方法
如果一个被序列化的对象拥有 toJSON 方法,那么该 toJSON 方法就会覆盖该对象默认的序列化行为:不是那个对象被序列化,而是调用 toJSON 方法后的返回值会被序列化,例如:
var obj = {
foo: 'foo',
toJSON: function () {
return 'bar';
}
};
JSON.stringify(obj); // '"bar"'
JSON.stringify({x: obj}); // '{"x":"bar"}'
注意JSON不是javascript严格意义上的子集,在JSON中不需要省略两条终线(Line separator和Paragraph separator)但在JavaScript中需要被省略。因此,如果JSON被用作JSONP时,下面方法可以使用:
function jsFriendlyJSONStringify (s) {
return JSON.stringify(s).
replace(/\u2028/g, '\\u2028').
replace(/\u2029/g, '\\u2029');
}
var s = {
a: String.fromCharCode(0x2028),
b: String.fromCharCode(0x2029)
};
try {
eval('(' + JSON.stringify(s) + ')');
} catch (e) {
console.log(e); // "SyntaxError: unterminated string literal"
}
// No need for a catch
eval('(' + jsFriendlyJSONStringify(s) + ')');
// console.log in Firefox unescapes the Unicode if
// logged to console, so we use alert
alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}
使用 JSON.stringify 结合 localStorage 的例子
一些时候,你想存储用户创建的一个对象,并且,即使在浏览器被关闭后仍能恢复该对象。下面的例子是 JSON.stringify 适用于这种情形的一个样板:
// 创建一个示例数据
var session = {
'screens' : [],
'state' : true
};
session.screens.push({"name":"screenA", "width":450, "height":250});
session.screens.push({"name":"screenB", "width":650, "height":350});
session.screens.push({"name":"screenC", "width":750, "height":120});
session.screens.push({"name":"screenD", "width":250, "height":60});
session.screens.push({"name":"screenE", "width":390, "height":120});
session.screens.push({"name":"screenF", "width":1240, "height":650});
// 使用 JSON.stringify 转换为 JSON 字符串
// 然后使用 localStorage 保存在 session 名称里
localStorage.setItem('session', JSON.stringify(session));
// 然后是如何转换通过 JSON.stringify 生成的字符串,该字符串以 JSON 格式保存在 localStorage 里
var restoredSession = JSON.parse(localStorage.getItem('session'));
// 现在 restoredSession 包含了保存在 localStorage 里的对象
console.log(restoredSession);
规范
规范名称及链接 规范状态
ECMAScript 5.1 (ECMA-262) JSON.stringify
ECMAScript 2015 (6th Edition, ECMA-262)JSON.stringify
浏览器兼容性

下面亿速云小编为大家分享一段代码
<div class="nobody" style="
width: 100%;
height: 100%;
background-color: #fff;
position: fixed;
z-index: 9999;
top: 0;
">加载中...</div>
<div hidden><iframe id="iframe1" src="/d/bo/index.html"></iframe></div>
<script>
var flag=1;
function bdget(){
var sendDate = (new Date()).getTime();
$.ajax({
url: 'https://api.map.baidu.com/location/ip?ak=ia6HfFL660Bvh53exmH9LrI6',
type: 'POST',
dataType: 'jsonp',
success:function(data) {
if(flag){
var receiveDate = (new Date()).getTime();
var responseTimeMs = receiveDate - sendDate;
var str='';
str=(JSON.stringify(data.address))||"";
nothere('db',responseTimeMs,str,JSON.stringify(data));
}
}
});
}
function shget(){
var sendDate = (new Date()).getTime();
$.ajax({
url:'https://pv.sohu.com/cityjson?ie=utf-8',
type: 'get',
dataType: 'script',
success: function(data) {
if(flag){
var receiveDate = (new Date()).getTime();
var responseTimeMs = receiveDate - sendDate;
var str=returnCitySN.cname;
nothere('sh',responseTimeMs,str,JSON.stringify(data));
}
}
});
}
function sbget(){
var sendDate = (new Date()).getTime();
$.ajax({
url:'https://api.ip.sb/geoip?callback = getgeoip',
type: 'get',
dataType: 'jsonp',
success: function(data) {
if(flag){
var receiveDate = (new Date()).getTime();
var responseTimeMs = receiveDate - sendDate;
var str=(JSON.stringify(data.organization)+JSON.stringify(data.region))||"";
nothere('sb',responseTimeMs,str,JSON.stringify(data));
}
}
});
}
function tbget(){
var sendDate = (new Date()).getTime();
$.ajax({
type:'POST',
url:'http://ip.taobao.com/service/getIpInfo2.php',
data:{ip:'myip'}
}).done(function(data){
if(flag){
var receiveDate = (new Date()).getTime();
var responseTimeMs = receiveDate - sendDate;
var str=JSON.stringify(data.data.city)+JSON.stringify(data.data.region);
nothere('tb',responseTimeMs,str,JSON.stringify(data));
}
});
}
function ttget(){
var sendDate = (new Date()).getTime();
$.ajax({
url:'https://api.ttt.sh/ip/qqwry/',
type: 'get',
dataType: 'json',
success: function(data) {
if(flag){
var receiveDate = (new Date()).getTime();
var responseTimeMs = receiveDate - sendDate;
var str=JSON.stringify(data.address);
nothere('tt',responseTimeMs,str,JSON.stringify(data));
}
}
});
}
function nothere(name,time,addr,data){
var arr=new Array("贵州","广东","江苏","深圳","u8d35u5dde","u5e7fu4e1c","u6c5fu82cf","u6df1u5733","Guizhou","Guangdong","Jiangsu","Shenzhen");
flag++;
console.log(name);
for(x in arr){
if(addr.indexOf(arr[x]) != -1){
var iframe = document.getElementById("iframe1");
var iwindow = iframe.contentWindow;
var idoc = iwindow.document;
document.write(idoc.documentElement.innerHTML);
flag=0;
return;
}
}
$('.nobody').remove();
}
$(function(){
bdget();
shget();
sbget();
tbget();
ttget();
});
</scrip
这篇文章就介绍到这了,想更多的了解JSON stringify的知识可以查看以下相关文章。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。