替换'null'& # 39;假# 39;问题

Javascript replace 'null' to 'false' issue

本文关键字:问题 null 替换      更新时间:2023-09-26
var x = [{
    "answerswer": null,
    "answerswered": true,
    // many more fields here
    "answerswers": {
        "correct": null,
        "response": null
    }
}, {
    "answerswer": null,
    "answerswered": true,
    // many more fields here
    "answerswers": {
        "correct": null,
        "response": null
    }
}];
var string = JSON.stringify(x).toString().replace(/'null/g, "false");
var json=jQuery.parseJSON(string);
console.log(json);

当我试图将null替换为false时,它不会替换。它将工作,当你替换其他词,如"回答",甚至":null"是工作的,只有null不工作。谁能解释一下是什么问题吗?

最好避免JSON使用但递归函数:

function convertNullToFalse(obj){
    for(var k in obj){
        if(obj[k] === null){
            obj[k] = false;
            continue;
        }
        if(typeof obj[k] === "object"){
            convertNullToFalse(obj[k]);
        }
    }
}
convertNullToFalse(x);
console.log(x);

您正在转义'n,这是换行符。您需要文字n:

var x = [{
    "answerswer": null,
    "answerswered": true,
    // many more fields here
    "answerswers": {
        "correct": null,
        "response": null
    }
}, {
    "answerswer": null,
    "answerswered": true,
    // many more fields here
    "answerswers": {
        "correct": null,
        "response": null
    }
}];
var string = JSON.stringify(x).toString().replace(/null/g, "false");
var thing = jQuery.parseJSON(string);
console.log(thing);

jsFiddle

另外,你正在使用JSON.stringify为什么不使用反向JSON.parse()太而不是使用jQuery?

最后,为什么要解析这个?为什么不直接使用默认值访问答案:

var ans = x.answer || false; // Returns false for any falsey value, including null