![](/img/trans.png)
[英]I JSON.stringify an object but how do I print out specific elements of object in Javascript
[英]How do I stringify a JSON object with a negative zero in JavaScript?
如何使用 JSON.stringify 將負零轉換為字符串 (-0)? JSON.stringify 似乎將負零轉換為表示正一的字符串。 有什么好的解決方法嗎?
var jsn = {
negative: -0
};
isNegative(jsn.negative) ? document.write("negative") : document.write("positive");
var jsonString = JSON.stringify(jsn),
anotherJSON = JSON.parse(jsonString);
isNegative(anotherJSON.negative) ? document.write("negative") : document.write("positive");
function isNegative(a)
{
if (0 !== a)
{
return !1;
}
var b = Object.freeze(
{
z: -0
});
try
{
Object.defineProperty(b, "z",
{
value: a
});
}
catch (c)
{
return !1;
}
return !0;
}
您可以分別為JSON.stringify
和JSON.parse
JSON.stringify
和JSON.stringify
函數。 替換器可以利用-0 === 0
、 1 / 0 === Infinity
和1 / -0 === -Infinity
來識別負零並將它們轉換為特殊字符串。 reviver 應該簡單地將特殊字符串轉換回-0
。 這是jsfiddle。
編碼:
function negZeroReplacer(key, value) {
if (value === 0 && 1 / value < 0)
return "NEGATIVE_ZERO";
return value;
}
function negZeroReviver(key, value) {
if (value === "NEGATIVE_ZERO")
return -0;
return value;
}
var a = {
plusZero: 0,
minusZero: -0
},
s = JSON.stringify(a, negZeroReplacer),
b = JSON.parse(s, negZeroReviver);
console.clear();
console.log(a, 1 / a.plusZero, 1 / a.minusZero)
console.log(s);
console.log(b, 1 / b.plusZero, 1 / b.minusZero);
輸出:
Object {plusZero: 0, minusZero: 0} Infinity -Infinity
{"plusZero":0,"minusZero":"NEGATIVE_ZERO"}
Object {plusZero: 0, minusZero: 0} Infinity -Infinity
我將負零轉換為"NEGATIVE_ZERO"
,但您可以使用任何其他字符串,例如"(-0)"
。
您可以使用帶有替換函數的 JSON.stringify 將負零更改為特殊字符串(如前面的答案所述),然后使用全局字符串替換將這些特殊字符串更改回生成的 json 字符串中的負零。 前任:
function json(o){ return JSON.stringify(o,(k,v)=> (v==0&&1/v==-Infinity)?"-0.0":v).replace(/"-0.0"/g,'-0') } console.log(json({'hello':0,'world':-0}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.