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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。